Search code snippets, questions, articles...

Extract integer values from a string in Python

If you have a string that contains numbers and you want to get those numbers out, you can use the Python built-in functions int(), isdigit() to extract the integer values from the string. In this post, we will show you multiple methods to do that.
my_str = "We have 100 frontend and 120 backend programmers in 10 companies"

result = [int(x) for x in my_str.split() if x.isdigit()]

print("Integer values in string are: ", result)
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

Output

Integer values in string are:  [100, 120, 10]

Solution 1: Using split(), isdigit() and List comprehension

Given a string, the task is to extract only the integers from the string and print them. This can be done using the split() method and isdigit() method. The split() method returns a list of substrings that are separated by a given delimiter. The isdigit() method returns True if all characters in the string are digits and there is at least one character, False otherwise.

List comprehension can be used to iterate over the list returned by the split() method and isdigit() method to check if each substring is a digit or not. If it is a digit, then it can be added to a list. Finally, the list of integers can be printed.

Code example 1

my_str = "There are 10 rabbits, 50 dogs and 20 cats in this area 52"

result = [int(x) for x in my_str.split() if x.isdigit()]

print(result)

Output

[10, 50, 20, 52]

The above code sets the variable my_str to a string containing numbers and words. It then uses a list comprehension to create a new list, result, which contains only the numbers from my_str, converted to integers. Finally, it prints the contents of the result.

Code example 2: without using split() - This can be helpful when you don't have spaces between numbers and words

my_str = "abc1de4fg8ij5k7"

result = [int(x) for x in my_str if x.isdigit()]

print(result)

Output

[1, 4, 8, 5, 7]

Solution 2: Using For loop

We can also use Python For loop to iterate over the string words and characters and can extract integer values from it. Below are some code examples that will help you to understand it.

Example1: Using for loop and split

my_str = "There are 10 rabbits, 50 dogs and 20 cats in this area 52"

result = []

for x in my_str.split():
    if(x.isdigit()):
        result.append(int(x))
    
print(result)

Output

[10, 50, 20, 52]

Example 2: Without using split() function 

my_str = "There are 10 rabbits, 50 dogs and 20 cats in this area 52"

result = []

for x in my_str:
    if(x.isdigit()):
        result.append(int(x))
    
print(result)

Output

[1, 0, 5, 0, 2, 0, 5, 2]

Example 3

input_str = "abc1de4fg8ij5k7"

r = []
for x in input_str:
    if x.isdigit():
        r.append(int(x))
    
print(r)

Output

[1, 4, 8, 5, 7]

Solution 3: Using findall() function of regex re module

The re module in python has a findall() function which can be used to extract integer values from a string. The findall() function returns a list of all the matches it finds. The string can be either a literal string or a regular expression. If you want to extract only positive integers, you can use the following regular expression: [1-9][0-9]*

import re

mystr = "There are 20 pens, 10 pencils and 40 books here"

result = re.findall(r'\d+', mystr)

# list values in string format
print(result)

# list values in int format
result = list(map(int, result))

print(result)

Output

['20', '10', '40']
[20, 10, 40]

In the above code example

  1. The first line imports the 're' module which provides regular expression tools.
  2. The second line defines a string variable called mystr.
  3. The third line uses the findall() function from the 're' module to find all instances of one or more digits in the string and stores them in the 'result' variable.
  4. The fourth line converts the 'result' variable from a list of strings to a list of integers.
  5. The fifth line prints the new list of integers.

Using filter(), map() and isdigit() function

In Python, the isdigit() method is used to check whether the given string is a digit or not. This function is used in conjunction with map() and filter() functions to extract only the integer values from a string. The map() function applies isdigit() function to each element of the given iterable (i.e. list, tuple, etc.) and returns a list of the results. The filter() function filters the given iterable by eliminating the elements for which the isdigit() method returns False.

Thus, to extract only the integer values from a string, we need to use the map() and filter() functions along with the isdigit() method.

my_str = "We have 20 orange, 10 apples and 5 bananas"

result = list(map(int, filter(str.isdigit, my_str.split())))

print(result)

Output

[20, 10, 5]

In the above code example, the map() function applies the int function to every element in the my_str list. The filter function checks if every element in the my_str list is a digit and returns a list of only the digit elements. Finally, the print function prints out the resulting list.

Was this helpful?
0 Comments