Let's suppose I have this string:
s = "123(45)678"
How can I can get this list?
l = ['123','(','45',')','678']
Let's suppose I have this string:
s = "123(45)678"
How can I can get this list?
l = ['123','(','45',')','678']
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']
You can use re.findall
:
import re
s = "123(45)678"
final_data = re.findall('\d+|\(|\)', s)
print(final_data)
Output:
['123', '(', '45', ')', '678']
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)