Bad_Coder
Bad_Coder

Reputation: 1029

Split a string (on whitespace or punctuation) to get all numbers

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

Answers (2)

Padraic Cunningham
Padraic Cunningham

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

user2555451
user2555451

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

Related Questions