Split string and just get number in python?
14,864
Solution 1
If all your numbers are positive integers, you can do that without regular expressions by using the isdigit() method:
>>> text = "GoTo: 7018 6453 12654\n"
>>> [token for token in text.split() if token.isdigit()]
['7018', '6453', '12654']
Solution 2
>>> re.findall(r'\d+', 'GoTo: 7018 6453 12654\n')
['7018', '6453', '12654']
Solution 3
>>> import re
>>> re.findall("[0-9]+", "GoTo: 7018 6453 12654\n")
['7018', '6453', '12654']
>>>
Solution 4
You can follow your current method in sample 1 along with this code:
filter (lambda a: a != '', match1)
Solution 5
Try this:
import re
splitter = re.compile(r'\d+')
match1 = splitter.findall("GoTo: 7018 6453 12654\n")
print match1
Related videos on Youtube
Author by
Am1rr3zA
I am interested in: 1- Big Data 2- Programming 3- Dota All Stars 4- new technology
Updated on December 30, 2020Comments
-
Am1rr3zA about 3 years
I have a string like
"GoTo: 7018 6453 12654\n"
I just want get the number something like this['7018', '6453', '12654']
, I tries regular expression but I can't split string to get just number here is my code:Sample 1:
splitter = re.compile(r'\D'); match1 = splitter.split("GoTo: 7018 6453 12654\n") my output is: ['', '', '', '', '', '', '', '', '7018', '6453', '12654', '']
Sample 2:
splitter = re.compile(r'\W'); match1 = splitter.split("GoTo: 7018 6453 12654\n") my output is: ['GoTo', '', '7018', '6453', '12654', '']