Issue
this is the JSON I am getting from the website :
[
{
"id":"8-23p-0",
"step":"",
"html":"<p>1</p>",
"link":"",
"commentCount":0
},
{
"id":"8-23p-1",
"step":"1",
"html":"<p>2</p>",
"link":"",
"commentCount":0
},
{
"id":"8-23p-2",
"step":"2",
"html":"<p>3</p>",
"link":"",
"commentCount":0
},
{
"id":"8-23p-3",
"step":"3",
"html":"<p>4</p>",
"link":"",
"commentCount":0
},
{
"id":"8-23p-4",
"step":"4",
"html":"<p>5</p>",
"link":"",
"commentCount":0
}
]
and I am writing this code to get all the HTML from that
html_values = []
for i in answer2:
html_values.append(i.get("html"))
by the above code i am getting all the html with type of list
but I want to add a heading for every step like :
expected output :
<h>step 1</h>
<p>1</p>
<h>step 2</h>
<p>2</p>
<h>step 3</h>
<p>3</p>
<h>step 4</h>
<p>4</p>
<h>step 5</h>
<p>5</p>
I want to get the output like above please help me Thanks in before
Solution
Assuming you want to use the step
value from your JSON, you can use a list comprehension with an f-string
to format it:
html_values = [f'<h>step {a["step"]}</h>{a["html"]}' for a in answer2]
Output:
[
'<h>step </h><p>1</p>',
'<h>step 1</h><p>2</p>',
'<h>step 2</h><p>3</p>',
'<h>step 3</h><p>4</p>',
'<h>step 4</h><p>5</p>'
]
If however you want the step number to reflect the entry in the list, then you can use enumerate
to generate the step numbers e.g.
html_values = [f'<h>step {i}</h>{a["html"]}' for i, a in enumerate(answer2, 1)]
Output:
[
'<h>step 1</h><p>1</p>',
'<h>step 2</h><p>2</p>',
'<h>step 3</h><p>3</p>',
'<h>step 4</h><p>4</p>',
'<h>step 5</h><p>5</p>'
]
In both cases you can get the entire output as a string using join
e.g.
print(''.join(html_values))
Answered By - Nick
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.