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
  • 161,711
  • 18
  • 231
  • 272
amir jj
  • 224
  • 2
  • 17

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
  • 100,514
  • 17
  • 155
  • 179