4

Is there a way to split a string in Python using multiple delimiters instead of one? split seems to take in only one parameter as delimiter.

Also, I cannot import the re module. (This is the main stumbling block really.)

Any suggestions on how I should do it?

Thanks!

2
  • 4
    What is the problem with importing re? What error does it give you? Commented Oct 29, 2012 at 19:51
  • I'm working on a Python UDF for Pig with a jython jar which is giving me issues. Working off an existing system here. Not inclined to fight legacy. I only need to use 3 delimiters. The number of delimiters is not a parameter. Commented Oct 29, 2012 at 19:54

2 Answers 2

9

In order to split on multiple sequences you could simply replace all of the sequences you need to split on with just one sequence and then split on that one sequence.

So

s = s.replace("z", "s")
s.split("s")

Will split on s and z.

Sign up to request clarification or add additional context in comments.

Comments

1

Generic approach for a list of splitters, please, someone can write this with less code?

Initializing vars:

>>> splits = ['.', '-', ':', ',']
>>> s='hola, que: tal. be'

Splitting:

>>> r = [ s ]
>>> for p in splits:
...    r =  reduce(lambda x,y: x+y, map(lambda z: z.split(p), r ))

Results:

>>> r
['hola', ' que', ' tal', ' be']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.