Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string with "(" and ")" and keep the delimiters (Python) [duplicate]

Tags:

python

regex

Let's suppose I have this string:

s = "123(45)678"

How can I can get this list?

l = ['123','(','45',')','678']
like image 213
Smok Avatar asked Oct 29 '17 15:10

Smok


2 Answers

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']
like image 138
DeepSpace Avatar answered Oct 02 '22 15:10

DeepSpace


You can use re.findall:

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

Output:

['123', '(', '45', ')', '678']
like image 31
Ajax1234 Avatar answered Oct 02 '22 15:10

Ajax1234