Home > Back-end >  Add single quotes around string in python
Add single quotes around string in python

Time:12-27

I have converted list to string. but after conversion I am getting string without single quote around the string

for eg:

items = ['aa','bb','cc']
items = ','.join(items)

output is : aa,bb,cc

expected output: 'aa','bb','cc'

CodePudding user response:

You could use a list comprehension to quote the individual strings in the list:

items = ['aa','bb','cc']
items = ','.join([f"'{i}'" for i in items])
print(items)  # 'aa','bb','cc'

CodePudding user response:

One way to accomplish this is by passing the list into a string formatter, which will place the outer quotes around each list element. The list is mapped to the formatter, then joined, as you have shown.

For example:

','.join(map("'{}'".format, items))

Output:

"'aa','bb','cc'"
  • Related