[SOLVED] How to form a string using list comprehension?

Issue

I am trying to form a string using a list.

If the list only has a single element e.g. l = [10] then the string should be 10.

If there are multiple elements e.g. l = [10,20,30] then the string should be 10,20,30.

I tried but it always appends extra , at the end.

"".join("%s," % x for x in l)

This produces 10, and 10,20,30, for the above lists.

Solution

Just use the following:

','.join(str(n) for n in l)

Answered By – Vadim Landa

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *