How to Get Integer Values from a String in Python

How to get integer values from a string in 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]

How to extract numbers from a string in Python?

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.

Extract Number from String in Python

You can filter the string by digits using str.isdigit method,

>>> int(filter(str.isdigit, str1))
3158

Extracting integer values from a string on Python

For multiple pairs of parenthesis in the string I think it is best to use a regex like so:

import re

output = '''Scan results for BrainS (192.168.43.111)
Scan results for Slave (192.168.43.107)
Scan results for SlaveSmall (192.168.43.242)'''

f = re.findall(r'\(([^()]+)\)',output)
>>>['192.168.43.111', '192.168.43.107', '192.168.43.242']

Try it here!

Getting the integer value from a list of strings

You can use regex to do it. Then create a dictionary to store all values:

import re

Loops = ['Loop 0 from point number 0 to 965',
'Loop 1 from point number 966 to 1969',
'Loop 2 from point number 1970 to 2961']
d = {}
for index, value in enumerate(Loops):
m = re.findall(r'\d+ to \d+', value)
m = [i.split('to') for i in m]
d[f'LoopStart{index+1}'] = int(m[0][0])
d[f'LoopEnd{index+1}'] = int(m[0][-1])

print(d)

Output:

{'LoopStart1': 0, 'LoopEnd1': 965, 'LoopStart2': 966, 'LoopEnd2': 1969, 'LoopStart3': 1970, 'LoopEnd3': 2961}

Explanation:

This line gets the index and item of that loop. i.e. index = 0,1,2... and value = 'Loop 0 from...', 'Loop 1 from ....'

for index, value in enumerate(Loops):

This line finds all the strings which start with a number, have 'to' in between, and end with a number.

m = re.findall(r'\d+ to \d+', value) 

This line splits the m string by to.

m = [i.split('to') for i in m]

This line adds the loop item with starting value in a dictionary called d

d[f'LoopStart{index+1}'] = int(m[0][0])

This line adds the loop item with an ending value in a dictionary called d

d[f'LoopEnd{index+1}'] = int(m[0][-1])

Also, this f'{value}' of creating strings is called f-strings.

Extract int from string in Pandas

You can convert to string and extract the integer using regular expressions.

df['B'].str.extract('(\d+)').astype(int)

How can I check if a string represents an int, without using try/except?

If you're really just annoyed at using try/excepts all over the place, please just write a helper function:

def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False

>>> print RepresentsInt("+123")
True
>>> print RepresentsInt("10.0")
False

It's going to be WAY more code to exactly cover all the strings that Python considers integers. I say just be pythonic on this one.

How do I parse a string to a float or int?

>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545


Related Topics



Leave a reply



Submit