1

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.

1
  • How do you intend to convert the Unicode to bytes? Commented Sep 16, 2013 at 15:42

6 Answers 6

6

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

result = "('%s')" % "','".join(mylist)
Sign up to request clarification or add additional context in comments.

Comments

1

What about this:

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

Comments

0

Try this:

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

Comments

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

Comments

0

What about repr()?

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

More info on repr()

Comments

0

Here is another variation:

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

Output:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.