Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String splitting in Python

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!

like image 804
Navneet Avatar asked Dec 27 '22 15:12

Navneet


2 Answers

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.

like image 122
jmh Avatar answered Dec 31 '22 13:12

jmh


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']
like image 30
dani herrera Avatar answered Dec 31 '22 12:12

dani herrera