Reputation:
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?
Upvotes: 2
Views: 77
Reputation: 304137
For this special case, this is ~17 times faster than ", ".join()
>>> x = "['dogs', 'cats']"
>>> repr(x)[1:-1]
"'dogs', 'cats'"
Upvotes: 1
Reputation: 250921
Use str.join
and repr
:
>>> x = ['dogs', 'cats']
>>> ", ".join(map(repr,x))
"'dogs', 'cats'"
or:
>>> ", ".join([repr(y) for y in x])
"'dogs', 'cats'"
Upvotes: 3