convert a list into a single string consisting with double quotes and separated by comma

Question:

I have met a problem to convert a list: list=['1','2','3'] into ' "1","2","3" '.

My code is:

str(",".join('"{}"'.format(i) for i in list))

but my output is:
"1","2","3" instead of ' "1","2","3" '

May I have your suggestion? Thanks.

Asked By: derec

||

Answers:

I see you don’t want to just prepend/append the needed substrings(the single quote and white space) to the crucial string.
Here’s a trick with str.replace() function:

lst = ['1','2','3']
result = "' - '".replace('-', ",".join('"{}"'.format(i) for i in lst))

print(result)

The output:

' "1","2","3" '

  • "' - '" – acts as a placeholder

Or the same with additional str.format() function call:

result = "' {} '".format(",".join('"{}"'.format(i) for i in lst))
Answered By: RomanPerekhrest
list = ['1','2','3', '5']
result = "' - '".replace('-', ",".join('"{}"'.format(i) for i in list)) 
# "' - '" - acts as a placeholder
print(result) # ' "1","2","3","5" '
Answered By: Avnish Jayaswal
lst = ['1','2','3']
result = ','.join(map(lambda x: '"{}"'.format(x), lst))
print(result)
'"1","2","3"'

I first started out putting it in a DataFrame and extracting to the iobuffer using to_csv. That seemed overly complex. The above was the most Pythonic that I could come up with. I did not need the extra spaces before and after, but you can easily add those by concatenating with plus signs or using a another format() statement.

Answered By: Dan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.