简体   繁体   中英

How to extract string from python list?

Assuming a python array "myarray" contains:

mylist = [u'a',u'b',u'c']

I would like a string that contains all of the elements in the array, while preserving the double quotes like this (notice how there are no brackets, but parenthesis instead):

result = "('a','b','c')"

I tried using ",".join(mylist) , but it gives me the result of "a,b,c" and eliminated the single quotes.

您距离很近,这就是我要做的:

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

What about this:

>>> mylist = [u'a',u'b',u'c']
>>> str(tuple(map(str, mylist)))
"('a', 'b', 'c')"

What about repr() ?

>>> repr(tuple(mylist))
"(u'a', u'b', u'c')"

More info on repr()

尝试这个:

result = "({})".format(",".join(["'{}'".format(char) for char in mylist]))
>>> l = [u'a', u'b', u'c']
>>> str(tuple([str(e) for e in l]))
"('a', 'b', 'c')"

Calling str on each element e of the list l will turn the Unicode string into a raw string. Next, calling tuple on the result of the list comprehension will replace the square brackets with parentheses. Finally, calling str on the result of that should return the list of elements with the single quotes enclosed in parentheses.

Here is another variation:

mylist = [u'a',u'b',u'c']
result = "\"{0}\"".format(tuple(mylist))
print(result)

Output:

"('a', 'b', 'c')"    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM