Last modified: Apr 10, 2023 By Alexander Williams
2 Ways to Get int From String In Python
Using regex
Get First Number:
import re # Import re Module
string = "hello my name is Mark i'm 20 years old" # String
# "/d" = Returns a match where the string contains digits (numbers from 0-9)
# "+" = One or more occurrences
search = re.search("\d+", string).group() # Search
print(search) # Print Result
Output:
20
Get all Numbers:
import re # Import re Module
string = "hello my name is Mark i'm 20 years old. i have 300 cats" # String
find_all = re.findall("\d+", string) # Find All int
print(find_all) # Result
Output:
['20', '300']
Using isdigit() built-function
Loop Way:
# Define a string to be tested
string = "Hello my name is Mark i'm 20 years old. i have 300 cats"
# Split the string into a list of words
split_string = string.split()
# Initialize an empty list to store the extracted integers
our_integers = []
# Iterate through each word in the list
for i in split_string:
# Check if the word is a digit using the isdigit() method
if i.isdigit():
# If the word is a digit, append it to the our_integers list
our_integers.append(i)
# Print the list of extracted integers
print(our_integers)
Output:
['20', '300']
List comprehension:
# Define a string to be tested
string = "Hello my name is Mark i'm 20 years old. i have 300 cats"
# Use a list comprehension to extract integers from the string
interegs = [i for i in string.split() if i.isdigit()]
# Print the list of extracted integers
print(interegs)
Output:
['20', '300']