There are many methods to get integer form string, so in this post, we'll learn how to get int from str, the first method is using Regex and the second is using isdigit() built-function

1. Getting integer from string by using regex (method #1)

Example 1:


import re
#string
string = "hello my name is Mark i'm 20 years old"

#search
# "/d" = Returns a match where the string contains digits (numbers from 0-9)
# "+" = One or more occurrences
search = re.search("\d+", string).group()

#print
print(search)

output

20

Example 2: finding all integers in a string

if you want to get all integers from string you need to user "findall()"


#string
string = "hello my name is Mark i'm 20 years old. i have 300 cats"


#findall integers ["20" and "300"]
find_all = re.findall("\d+", string)

#print results
print(find_all)

output

['20', '300']

as you can see, we have got all integers as list

2. Getting integer from string by using isdigit() built-function (method #2)

How this method works ?

first we'll spilt the string then check item by item if is a string

Example 1:


test_string = "Hello my name is Mark i'm 20 years old. i have 300 cats"


split_string = test_string.split() #split str into list

our_integers = []


for i in split_string:
    if i.isdigit():
        our_integers.append(i)
    
    
print(our_integers)    

output

['20', '300']

Example 2:

let's rewrite the above example with the sort code [good code]


test_string = "Hello my name is Mark i'm 20 years old. i have 300 cats"

our_interegs = [i for i in test_string.split() if i.isdigit()]

print(our_interegs)   

output

['20', '300']

3. Summary

in this article, we've learned two methods to get number from string, Regex, and isdigit() built-function, as far as I know, the second method is more expensive than the first method

English today is not an art to be mastered it's just a tool to use to get a result