1

I've string which includes some irrelevant characters for example :

"t1, t2, t3"

If I'm splitting it by split(",") method I'm getting a list where second and third items include also the white space.

How can I split required string with multiply separator ?

1

5 Answers 5

6

Either split them by ", " (note the space) or strip the words after that:

[e.strip() for e in "t1, t2, t3,t4".split(",")]
>>> ['t1', 't2', 't3', 't4']
Sign up to request clarification or add additional context in comments.

Comments

4

If you don't need whitespace you could use :

"t1, t2, t3,t4".replace(" ", "").split(",")

1 Comment

Thank you for this answer. It seems most people are recommending regular expressions, but I'm using this on an embedded system and each new library I have to pull in complicates it further. Sometimes simpler is better.
2

If there are arbitrary spaces after the commas, just strip the whitespace using a list comprehension:

[t.strip() for t in inputstring.split(',')]

or use a regular expression split (somewhat overkill in this situation):

import re

re.split(r',\s*', inputstring)

Demonstration:

>>> inputstring = 't1, t2, t3,t4,   t5'
>>> [t.strip() for t in inputstring.split(',')]
['t1', 't2', 't3', 't4', 't5']
>>> import re
>>> re.split(r',\s*', inputstring)
['t1', 't2', 't3', 't4', 't5']

Comments

1

Did you try the obvious:

>>> "t1, t2, t3".split(', ')
['t1', 't2', 't3']

2 Comments

It's not so simple, what if I'll have 3 types of separators ?
@user301639: Then you should have said that in your question. :-)
0

Use strip().

s = "t1, t2, t3"
s = [x.strip() for x in s.split(",")]
print s

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.