Rolando
Rolando

Reputation: 62704

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.

Upvotes: 1

Views: 38881

Answers (6)

Harold Henson
Harold Henson

Reputation: 31

Here is another variation:

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

Output:

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

Upvotes: 0

Diego Herranz
Diego Herranz

Reputation: 2947

What about repr()?

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

More info on repr()

Upvotes: 0

U-DON
U-DON

Reputation: 2140

>>> 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.

Upvotes: 0

Samy Arous
Samy Arous

Reputation: 6812

Try this:

result = "({})".format(",".join(["'{}'".format(char) for char in mylist]))

Upvotes: 0

Daniel Figueroa
Daniel Figueroa

Reputation: 10696

You were quite close, this is how I would've done it:

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

Upvotes: 6

arshajii
arshajii

Reputation: 129587

What about this:

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

Upvotes: 1

Related Questions