user1971598
user1971598

Reputation:

String of strings for arbitrary amount, python

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

Answers (3)

John La Rooy
John La Rooy

Reputation: 304137

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

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

Upvotes: 1

Andrew Clark
Andrew Clark

Reputation: 208455

I would use the following:

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

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

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

Related Questions