snippetpythonCritical
How to extract numbers from a string in Python?
Viewed 0 times
howpythonextractnumbersstringfrom
Problem
I would like to extract all the numbers contained in a string. Which is better suited for the purpose, regular expressions or the
Example:
Result:
isdigit() method?Example:
line = "hello 12 hi 89"Result:
[12, 89]Solution
If you only want to extract only positive integers, try the following:
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.
>>> 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.
Code Snippets
>>> txt = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in txt.split() if s.isdigit()]
[23, 11, 2]Context
Stack Overflow Q#4289331, score: 723
Revisions (0)
No revisions yet.