5

Let's suppose I have this string:

s = "123(45)678"

How can I can get this list?

l = ['123','(','45',')','678']
Smok
  • 67
  • 1
  • 4
  • 3
    @hek2mgl Not really, the question is also about **keeping** the delimiters – jadsq Oct 29 '17 at 15:16
  • The other question is about a regular expession split. This one is about string.split and much more straight forward – Wolfgang Fahl Dec 30 '20 at 07:53
  • 1
    This question asks for the same solution, a capturing group wrapping the whole expression in a re.split. The duplicate mark should stay. – Ryszard Czech Dec 30 '20 at 22:28

3 Answers3

9

If you were only interested in '(' or ')' then str.partition would have been sufficient.

Since you have multiple delimiters AND you want to keep them, you can use re.split with a capture group:

import re

s = "123(45)678"

print(re.split(r'([()])', s))
# ['123', '(', '45', ')', '678']
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
2

You can use re.findall:

import re
s = "123(45)678"
final_data = re.findall('\d+|\(|\)', s)
print(final_data)

Output:

['123', '(', '45', ')', '678']
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

If you don't want to use re, then you could try this:

s = "123(45)678"
finalist = []
tempstring = ''
for e in s:
    if e!='(' and e!=')':
        tempstring+=e
    else:
        finalist.append(tempstring)
        finalist.append(e)
        tempstring=''
finalist.append(tempstring)
print(finalist)
whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44