0

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']
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
amir jj
  • 226
  • 2
  • 18

1 Answers1

1

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']
Mazdak
  • 105,000
  • 18
  • 159
  • 188