1

Possible Duplicate:
Python: Split string with multiple delimiters

I have a small syntax problem. I have a string and another string that has a list of seperators. I need to split it via the .split method.

I can't seem to figure out how, this certainly gives a Type error.

String.split([' ', '{', '='])

How can i split it with multiple seperators?

Community
  • 1
  • 1
Aayush Agrawal
  • 1,334
  • 1
  • 11
  • 21

5 Answers5

7

str.split() only accepts one separator.

Use re.split() to split using a regular expression.

import re

re.split(r"[ {=]", "foo bar=baz{qux")

Output:

['foo', 'bar', 'baz', 'qux']
1

That's not how the built-in split() method works. It simply uses a single string as the separator, not a list of single-character separators.

You can use regular-expression based splitting, instead. This would probably mean building a regular expression that is the "or" of all your desired delimiters:

splitters = "|".join([" ", "{", "="])
re.split(splitters, my_string)
unwind
  • 378,987
  • 63
  • 458
  • 590
0

You can do this with the re (regex) library like so:

import re
result=re.split("[abc]", "my string with characters i want to split")

Where the characters in the square brackets are the characters you want to split with.

Will Richardson
  • 7,372
  • 6
  • 42
  • 54
0

Use split from regular expressions instead:

>>> import re
>>> s = 'toto + titi = tata'
>>> re.split('[+=]', s)
['toto ', ' titi ', ' tata']
>>> 
Emmanuel
  • 13,267
  • 11
  • 46
  • 70
0
import re
string_test = "abc cde{fgh=ijk"
re.split('[\s{=]',string_test)
Shawn Zhang
  • 1,532
  • 1
  • 11
  • 18
  • 1
    The OP didn't include *every* whitespace and bars `|` in the list of his delimiters. –  Nov 12 '12 at 08:48