Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract numbers from a string in Python?

I would like to extract all the numbers contained in a string. Which is better suited for the purpose, regular expressions or the isdigit() method?

Example:

line = "hello 12 hi 89" 

Result:

[12, 89] 
like image 315
pablouche Avatar asked Nov 27 '10 00:11

pablouche


People also ask

How do I extract numbers from a string in Python?

To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string. If no character is a digit in the given string then it will return False.


2 Answers

If you only want to extract only positive integers, try the following:

>>> txt = "h3110 23 cat 444.4 rabbit 11 2 dog" >>> [int(s) for s in txt.split() if s.isdigit()] [23, 11, 2] 

I would argue that this is better than the regex example because you don't need another module and it's more readable because you don't need to parse (and learn) the regex mini-language.

This will not recognize floats, negative integers, or integers in hexadecimal format. If you can't accept these limitations, jmnas's answer below will do the trick.

like image 189
fmark Avatar answered Oct 22 '22 09:10

fmark


I'd use a regexp :

>>> import re >>> re.findall(r'\d+', 'hello 42 I\'m a 32 string 30') ['42', '32', '30'] 

This would also match 42 from bla42bla. If you only want numbers delimited by word boundaries (space, period, comma), you can use \b :

>>> re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30') ['42', '32', '30'] 

To end up with a list of numbers instead of a list of strings:

>>> [int(s) for s in re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30')] [42, 32, 30] 
like image 42
Vincent Savard Avatar answered Oct 22 '22 07:10

Vincent Savard