How to convert list into string with quotes in python
19,034
Solution 1
This seems to be the only solution so far that isn't a hack...
>>> mylist = [1,2,3]
>>> ','.join("'{0}'".format(x) for x in mylist)
"'1','2','3'"
This can also be written more compactly as:
>>> ','.join(map("'{0}'".format, mylist))
"'1','2','3'"
Solution 2
>>> mylist = [1,2,3]
>>> str([str(x) for x in mylist]).strip("[]")
"'1','2','3'"
Solution 3
as a simple hack, why don't you..
mystring = "'%s'" %"','".join(mylist)
wrap the result of your commands in quotes?
Solution 4
you can do this as well
mylist = [1, 2, 3]
mystring = str(map(str, mylist)).strip("[]")
Solution 5
OR regular repr
:
>>> l=[1,2,3]
>>> ','.join(repr(str(i)) for i in l)
"'1','2','3'"
>>>
Author by
Rao
Updated on June 24, 2022Comments
-
Rao almost 2 years
i have a list and want it as a string with quotes
mylist = [1,2,3]
require O/P as
myString = "'1','2','3'"
i tried
mystring = '\',\''.join(mylist)
it gave me result as
mystring = "1','2','3"
first and last quotes (') are missing