You can use regular expressions or string processing functions to extract numbers from strings in Python.
Implemented using regular expressions:
import re
s = 'Hello 12345 World'
nums = re.findall(r'\d+', s)
print(nums) # ['12345']
re
The function of the module is used here findall
, and the regular expression is used \d+
to match the numbers in the string, and the returned result is the number in the form of a list.
Implemented using string processing functions:
s = 'Hello 12345 World'
nums = ''.join(filter(str.isdigit, s))
print(nums) # '12345'
Here, filter
a function is used to filter out the numbers in the string, and then join
a function is used to concatenate the numbers into a string.