Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert list into string with quotes in python

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

like image 440
Rao Avatar asked Nov 28 '22 03:11

Rao


2 Answers

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'"

Or, using an f-string:

>>> mylist = [1,2,3]
>>> ','.join(f"'{x}'" for x in mylist)
"'1','2','3'"
like image 72
jamylak Avatar answered Dec 10 '22 16:12

jamylak


>>> mylist = [1,2,3]
>>> str([str(x) for x in mylist]).strip("[]")
"'1','2','3'"
like image 31
atomh33ls Avatar answered Dec 10 '22 16:12

atomh33ls