Last modified: Jan 10, 2023 By Alexander Williams
python3: Getting int From String [easily]
In this tutorial, we'll learn how to get an int from a str, by using Regex (method #1) or isdigit() built-function (method #2).
1. Using regex
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. Using isdigit() built-function
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 way.
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