How to convert list into string with quotes in python

前端 未结 5 486
孤城傲影
孤城傲影 2020-12-11 21:12

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 my

相关标签:
5条回答
  • 2020-12-11 21:28
    >>> mylist = [1,2,3]
    >>> str([str(x) for x in mylist]).strip("[]")
    "'1','2','3'"
    
    0 讨论(0)
  • 2020-12-11 21:33

    OR regular repr:

    >>> l=[1,2,3]
    >>> ','.join(repr(str(i)) for i in l)
    "'1','2','3'"
    >>> 
    
    0 讨论(0)
  • 2020-12-11 21: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'"
    
    0 讨论(0)
  • 2020-12-11 21:37

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

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

    wrap the result of your commands in quotes?

    0 讨论(0)
  • 2020-12-11 21:41

    you can do this as well

    mylist = [1, 2, 3]
    mystring = str(map(str, mylist)).strip("[]")
    
    0 讨论(0)
提交回复
热议问题