8

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

Rao
  • 2,902
  • 14
  • 52
  • 70
  • 1
    How about you just take the result of your computation, and add single quotes around it as a second step: `mystring = "'"+mystring+"'"` – alexis Apr 17 '13 at 08:21

5 Answers5

35

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'"
WPWIV
  • 33
  • 8
jamylak
  • 128,818
  • 30
  • 231
  • 230
3
>>> mylist = [1,2,3]
>>> str([str(x) for x in mylist]).strip("[]")
"'1','2','3'"
Lee
  • 29,398
  • 28
  • 117
  • 170
2

as a simple hack, why don't you..

mystring = "'%s'" %"','".join(mylist)

wrap the result of your commands in quotes?

thkang
  • 11,215
  • 14
  • 67
  • 83
1

you can do this as well

mylist = [1, 2, 3]
mystring = str(map(str, mylist)).strip("[]")
ashokadhikari
  • 1,182
  • 3
  • 15
  • 29
1

OR regular repr:

>>> l=[1,2,3]
>>> ','.join(repr(str(i)) for i in l)
"'1','2','3'"
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114