Reputation: 101
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.
Upvotes: 2
Views: 4239
Reputation: 151
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.
Upvotes: 0
Reputation: 459
list = ['1','2','3', '5']
result = "' - '".replace('-', ",".join('"{}"'.format(i) for i in list))
# "' - '" - acts as a placeholder
print(result) # ' "1","2","3","5" '
Upvotes: 0
Reputation: 92854
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 placeholderOr the same with additional str.format()
function call:
result = "' {} '".format(",".join('"{}"'.format(i) for i in lst))
Upvotes: 2