2

Say we have a list whose elements are string items. So for example, x = ['dogs', 'cats'].

How could one go about making a new string "'dogs', 'cats'" for an arbitrary number of items in list x?

2
  • 1
    How would you treat items that contain the ' character? Commented Jun 18, 2013 at 21:00
  • In particular: Are you happy treating them exactly the same way that Python's repr function does (basically, that means replacing the outer quotes with double quotes if that's sufficient, backslash-escaping quotes if not), or do you want different rules? Commented Jun 18, 2013 at 21:05

3 Answers 3

3

Use str.join and repr:

>>> x = ['dogs', 'cats']
>>> ", ".join(map(repr,x))
"'dogs', 'cats'"

or:

>>> ", ".join([repr(y) for y in x])
"'dogs', 'cats'"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this works for me. Still trying to figure out difference between repr and str.
2

I would use the following:

', '.join(repr(s) for s in x)

Comments

1

For this special case, this is ~17 times faster than ", ".join()

>>> x = "['dogs', 'cats']"
>>> repr(x)[1:-1]
"'dogs', 'cats'"

Comments

Your Answer

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