Separate the string with "(" and ")" and save the delimiters (Python)

Suppose I have this line:

s = "123(45)678"

How can I get this list?

l = ['123','(','45',')','678']
+4
source share
3 answers

If you are only interested in '('or ')', then str.partitionit would be enough.

Since you have several separators and you want to keep them, you can use re.splitwith a capture group:

import re

s = "123(45)678"

print(re.split(r'([()])', s))
# ['123', '(', '45', ')', '678']
+6
source

You can use re.findall:

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

Conclusion:

['123', '(', '45', ')', '678']
+1
source

re, :

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)
0

Source: https://habr.com/ru/post/1688364/


All Articles