Reputation: 287
I have list like :
Input=['Name', 'Friendly Name', 'Place']
I want to convert it into a string like:
Output='Name, "Friendly Name", Place'
How can I do this in python.
Upvotes: 0
Views: 51
Reputation: 107
To turn a list into a string, like 0buz mentions you should use the join()
method of string objects.
", ".join(Input)
To quote strings with spaces in them, you can use a list comprehension to create a copy of the list with the necessary changes:
[ f'"{s}"' if ' ' in s else s for s in Input]
This iterates over each item s
in the list Input
, checking if ' ' (a space) is in the item. If it is, we concatenate a "
to the beginning and end of the s
and then append it to our list. Otherwise, we just append the item s
unchanged.
Putting them together:
Output = ", ".join([ f'"{s}"' if ' ' in s else s for s in Input])
Upvotes: 2
Reputation: 395
You can try something like this :
Input=['Name', 'Friendly Name', 'Place']
Input = ['"' + name + '"' if name.count(' ') > 0 else name for name in Input ]
", ".join(Input)
#result : 'Name, "Friendly Name", Place'
Upvotes: 2