amir jj amir jj - 3 years ago 83
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:


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

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

Answer Source

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']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download