0

I have following list in Python:

list = ["one", "two", "three", "four", "five"]

and would like to convert it to following string:

<field>one</field><field>two</field><field>three</field><field>four/field><field>five</field>

what is the most efficient way?

1 Answer 1

1

One way to do this would be:

"".join("<field>{}</field>".format(x) for x in list)

This uses a "list comprehension" to iterate through your list and apply a string format to each element. Then, the elements created that way are joined together into one big string to get the final result.

Sign up to request clarification or add additional context in comments.

7 Comments

thanks but instead '>' and '<' I am getting &lt; and &gt;
@bogumbiker: Well then there's more to what you're doing that you haven't shown. If you try the above interactively in a Python prompt, then it will produce the result you wanted. You are probably doing something like running this in a framework that automatically escapes HTML for you. If you want to generate raw HTML, you'll have to find a way to bypass that.
thanks for the hint. I am doing this inside lxml.builder perhaps that is why?
@bogumbiker: Yes, that's probably why. If you don't know how to solve that, then see Python: Injecting HTML content into a tag using lxml.html
it is a xml document and I am trying to do following: fields = "".join("<field>{}</field>".format(x) for x in list) doc = etree.fromstring(fields) but getting error lxml.etree.XMLSyntaxError: Extra content at the end of the document, line 1, column 20
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.