11
votes

See two examples how re.split() works:

>>> re.split(',', 'a,b')
['a', 'b']

but

>>> re.split('(,)', 'a,b')
['a', ',', 'b']

Why I get ',' in the list? How to avoid it?

I am asking, because I would like to make a split using an expression similar to 'xy(a|b)cd'.

2

2 Answers

16
votes

Use a non-capturing group, like:

re.split('(?:,)', 'a,b')
2
votes

It works that way because it’s documented to work that way:

If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list.