How to add single quotes for each plain words without quotes which is separated by comma in python? [duplicate]
I have a following string:
s_tring = 'abcd,efgh,igkl,mnop,qrst,uvwx,yz'
I want to create a list and split it by commas and put quotes around each element like this:
some_list = '"abcd", "efgh", "igkl", "mnop", "qrst", "uvwx", "yz"'
I have tried doing something like this:
some_list = '","'.join(s_tring)
But it doesn't work.
In a single line using the split
and join
methods with a list comprehension.
s = 'abcd,efgh,igkl,mnop,qrst,uvwx,yz'
print(', '.join([f'"{w}"' for w in s.split(',')]))
# '"abcd", "efgh", "igkl", "mnop", "qrst", "uvwx", "yz"'
You must first split the original string into a list of strings and then you can put the quotes round them and finally join with a comma:
s_tring = 'abcd,efgh,igkl,mnop,qrst,uvwx,yz'
parts = s_tring.split(',')
parts = [f'"{part}"' for part in parts]
some_list = ', '.join(parts)
An alternative is to join the parts with quotes as well and finally add the missing quotes:
s_tring = 'abcd,efgh,igkl,mnop,qrst,uvwx,yz'
parts = s_tring.split(',')
some_list = '"' + '", "'.join(parts) + '"'
print(some_list)
Just split & join
string = 'abcd,efgh,igkl,mnop,qrst,uvwx,yz'
string = ', '.join([f'"{x}"' for x in string.split(',')])
print(string)
output
"abcd", "efgh", "igkl", "mnop", "qrst", "uvwx", "yz"