Reputation: 62704
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
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
Reputation: 2947
What about repr()
?
>>> repr(tuple(mylist))
"(u'a', u'b', u'c')"
More info on repr()
Upvotes: 0
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
Reputation: 6812
Try this:
result = "({})".format(",".join(["'{}'".format(char) for char in mylist]))
Upvotes: 0
Reputation: 10696
You were quite close, this is how I would've done it:
result = "('%s')" % "','".join(mylist)
Upvotes: 6
Reputation: 129587
What about this:
>>> mylist = [u'a',u'b',u'c']
>>> str(tuple(map(str, mylist)))
"('a', 'b', 'c')"
Upvotes: 1