0

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.

richa verma
  • 247
  • 2
  • 13
  • Does this answer your question? [Converting a list to a string](https://stackoverflow.com/questions/2906092/converting-a-list-to-a-string) – 0buz Mar 11 '20 at 12:08
  • Does this answer your question? [convert list to string in python](https://stackoverflow.com/questions/59591503/convert-list-to-string-in-python) – Ayushi Keshri Mar 11 '20 at 12:53

2 Answers2

2

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'
Louis Hulot
  • 357
  • 2
  • 13
2

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])
Deniz Genç
  • 107
  • 1
  • 8