amir jj amir jj - 1 month ago 5
Python Question

Save delimiters after parsing with `re` or `split`

I have some strings to parse like below, with two delimiters:

import re
str='Beautiful is:better than:ugly'
re.split(' |: ',str)


the output is:

['Beautiful','is','better','than','ugly']


I need to save delimiters in array too, Is there a way to do that like below output?

['Beautiful', ' ', 'is', ':', 'better', ' ', 'than', ':', 'ugly']

Answer

You need capture groups:

In [2]: import re

In [3]: str='Beautiful is:better than:ugly'

In [4]: re.split(r'( |:)',str)
Out[4]: ['Beautiful', ' ', 'is', ':', 'better', ' ', 'than', ':', 'ugly']
Comments