Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get integer values from a string in Python?
In Python, extracting integer values from strings is a common task when processing text data. Python provides several approaches including the filter() method, regular expressions, and string manipulation techniques.
Using filter() and isdigit() Methods
The filter() method creates a new iterator by filtering elements based on a condition. When combined with isdigit(), it extracts only the digit characters from a string ?
text = "There are 20 teams competing in the Premier League"
print("The given string is:")
print(text)
# Extract digits and join them
digits = ''.join(filter(str.isdigit, text))
if digits:
print("The number present in the string is:")
print(int(digits))
else:
print("No digits found")
The given string is: There are 20 teams competing in the Premier League The number present in the string is: 20
Using Regular Expressions
Regular expressions provide powerful pattern matching capabilities. The \d+ pattern matches one or more consecutive digits, making it ideal for extracting multiple numbers from text ?
import re
text = "There are 21 oranges, 13 apples and 18 bananas in the basket"
print("The given string is:")
print(text)
# Find all numbers in the string
numbers = re.findall(r'\d+', text)
integer_list = list(map(int, numbers))
print("The numbers present in the string are:")
print(integer_list)
The given string is: There are 21 oranges, 13 apples and 18 bananas in the basket The numbers present in the string are: [21, 13, 18]
Using split() and isdigit() Methods
This approach splits the string into words and checks each word to see if it contains only digits ?
text = "There are 21 oranges, 13 apples and 18 bananas in the basket"
print("The given string is:")
print(text)
# Split string and filter digits
numbers = []
for word in text.split():
# Remove punctuation and check if remaining is digit
clean_word = ''.join(char for char in word if char.isdigit())
if clean_word:
numbers.append(int(clean_word))
print("The numbers present in the string are:")
print(numbers)
The given string is: There are 21 oranges, 13 apples and 18 bananas in the basket The numbers present in the string are: [21, 13, 18]
Comparison of Methods
| Method | Best For | Returns | Handles Multiple Numbers |
|---|---|---|---|
filter() |
Single continuous number | Single integer | No |
| Regular expressions | Complex patterns | List of integers | Yes |
split() |
Word-separated numbers | List of integers | Yes |
Conclusion
Use regular expressions for the most flexible integer extraction from strings. The filter() method works best for single continuous numbers, while split() is effective for word-separated values.
