Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string and just get number in python?

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', '']
like image 528
Am1rr3zA Avatar asked Dec 29 '10 09:12

Am1rr3zA


People also ask

How do you only extract a number from a string in Python?

This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string.

How do you split a string into numbers in Python?

Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do I convert a string to a number in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .


2 Answers

>>> re.findall(r'\d+', 'GoTo: 7018 6453 12654\n')
['7018', '6453', '12654']
like image 164
moinudin Avatar answered Sep 24 '22 02:09

moinudin


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']
like image 34
Frédéric Hamidi Avatar answered Sep 21 '22 02:09

Frédéric Hamidi