Markum
Markum

Reputation: 4049

Splitting a list into a string

This is my list:

animals = ['dog', 'cat', 'mouse']

I want to split it so I end up with a string with the three strings inside the list, like this:

dog/cat/mouse

I have tried using the following code, but it just prints the original list:

print [e.split('/')[0] for e in animals]

Anything wrong?

Upvotes: 1

Views: 796

Answers (2)

the wolf
the wolf

Reputation: 35532

Join works great.

If you have a fixed string that you want to populate with a fixed number of list elements, you can also do this:

>>> '{}+{}-{}'.format(*(t for t in animals))
'dog+cat-mouse'

Upvotes: 0

Constantinius
Constantinius

Reputation: 35059

You don't want to split you want to join, somehow the reverse operation.

animals = ['dog', 'cat', 'mouse']
"/".join(animals)

Upvotes: 11

Related Questions