How to get integer values from a string in Python?

PythonStringInteger

Python Problem Overview


Suppose I had a string

string1 = "498results should get" 

Now I need to get only integer values from the string like 498. Here I don't want to use list slicing because the integer values may increase like these examples:

string2 = "49867results should get" 
string3 = "497543results should get" 

So I want to get only integer values out from the string exactly in the same order. I mean like 498,49867,497543 from string1,string2,string3 respectively.

Can anyone let me know how to do this in a one or two lines?

Python Solutions


Solution 1 - Python

>>> import re
>>> string1 = "498results should get"
>>> int(re.search(r'\d+', string1).group())
498

If there are multiple integers in the string:

>>> map(int, re.findall(r'\d+', string1))
[498]

Solution 2 - Python

An answer taken from ChristopheD here: https://stackoverflow.com/a/2500023/1225603

r = "456results string789"
s = ''.join(x for x in r if x.isdigit())
print int(s)
456789

Solution 3 - Python

Here's your one-liner, without using any regular expressions, which can get expensive at times:

>>> ''.join(filter(str.isdigit, "1234GAgade5312djdl0"))

returns:

'123453120'

Solution 4 - Python

if you have multiple sets of numbers then this is another option

>>> import re
>>> print(re.findall('\d+', 'xyz123abc456def789'))
['123', '456', '789']

its no good for floating point number strings though.

Solution 5 - Python

Iterator version

>>> import re
>>> string1 = "498results should get"
>>> [int(x.group()) for x in re.finditer(r'\d+', string1)]
[498]

Solution 6 - Python

>>> import itertools
>>> int(''.join(itertools.takewhile(lambda s: s.isdigit(), string1)))

Solution 7 - Python

With python 3.6, these two lines return a list (may be empty)

>>[int(x) for x in re.findall('\d+', your_string)]

Similar to

>>list(map(int, re.findall('\d+', your_string))

Solution 8 - Python

def function(string):  
    final = ''  
    for i in string:  
        try:   
            final += str(int(i))   
        except ValueError:  
            return int(final)  
print(function("4983results should get"))  

Solution 9 - Python

this approach uses list comprehension, just pass the string as argument to the function and it will return a list of integers in that string.

def getIntegers(string):
        numbers = [int(x) for x in string.split() if x.isnumeric()]
        return numbers

Like this

print(getIntegers('this text contains some numbers like 3 5 and 7'))

Output

[3, 5, 7]

Solution 10 - Python

Another option is to remove the trailing the letters using rstrip and string.ascii_lowercase (to get the letters):

import string
out = [int(s.replace(' ','').rstrip(string.ascii_lowercase)) for s in strings]

Output:

[498, 49867, 497543]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShiva Krishna BavandlaView Question on Stackoverflow
Solution 1 - PythonjamylakView Answer on Stackoverflow
Solution 2 - PythonSeperoView Answer on Stackoverflow
Solution 3 - PythonBobortView Answer on Stackoverflow
Solution 4 - PythonjacanterburyView Answer on Stackoverflow
Solution 5 - PythonJohn La RooyView Answer on Stackoverflow
Solution 6 - PythonCraig CitroView Answer on Stackoverflow
Solution 7 - Pythonhuseyin39View Answer on Stackoverflow
Solution 8 - PythonKishor SubediView Answer on Stackoverflow
Solution 9 - PythonLovely SharmaView Answer on Stackoverflow
Solution 10 - Pythonuser7864386View Answer on Stackoverflow