Reputation: 1029
I have a string
Mystring = "123 456 789, 234, 999|567 888[222"
I want to split this string for " "
","
"|"
, and "["
to get all the numbers in a list
Expected Output:-
List = ["123","456","789","234","999",567","888","222"]
I'm using following piece of code
Final_List = re.findall("(\d+?)[ ,|\]]",Mystring)
Actual Output:
["123","456","789",234","999",567"]
How can i get all the numbers here?
Upvotes: 1
Views: 759
Reputation: 180540
import string
tbl = string.maketrans(',|['," ")
print(Mystring.translate(tbl)).split()
['123', '456', '789', '234', '999', '567', '888', '222']
In [29]: import string
In [30]: %%timeit
....: tbl = string.maketrans(',|['," ")
....: (Mystring.translate(tbl)).split()
....:
1000000 loops, best of 3: 762 ns per loop
In [31]: import re
In [32]: timeit re.findall('\d+', Mystring)
100000 loops, best of 3: 2.99 µs per loop
Upvotes: 1
Reputation:
Instead of splitting the string, why not just get the numbers directly:
>>> import re
>>> Mystring = "123 456 789, 234, 999|567 888[222"
>>> re.findall('\d+', Mystring)
['123', '456', '789', '234', '999', '567', '888', '222']
>>>
\d+
has Python match one or more digits (a number).
Upvotes: 5