Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string with multiple delimiters in Python

I'm using regular expressions to split a string using multiple delimiters. But if two of my delimiters occur next to each other in the string, it puts an empty string in the resulting list. For example:

re.split(',|;', "This,is;a,;string")

Results in

['This', 'is', 'a', '', 'string']

Is there any way to avoid getting '' in my list without adding ,; as a delimiter?

like image 585
David DeMar Avatar asked May 01 '12 03:05

David DeMar


People also ask

How do you split with multiple separators?

Use the String. split() method to split a string with multiple separators, e.g. str. split(/[-_]+/) . The split method can be passed a regular expression containing multiple characters to split the string with multiple separators.

Can split () take multiple arguments?

split() only works with one argument, so I have all words with the punctuation after I split with whitespace.

How do you split a string into multiple strings in Python?

Split String in Python. To split a String in Python with a delimiter, use split() function. split() function splits the string into substrings and returns them as an array.


1 Answers

Try this:

import re
re.split(r'[,;]+', 'This,is;a,;string')
> ['This', 'is', 'a', 'string']
like image 50
Óscar López Avatar answered Sep 20 '22 18:09

Óscar López