How to extract numbers from a string using Python?
You can extract numbers from a string using either regular expressions or built-in string methods.
Utilize regular expressions:
import re
s = "abc123def456"
numbers = re.findall(r'\d+', s)
print(numbers) # ['123', '456']
Utilizing string methods:
s = "abc123def456"
numbers = ''.join(filter(str.isdigit, s))
print(numbers) # '123456'
If you need to extract decimal numbers, you can make some modifications.
import re
s = "abc1.23def4.56"
numbers = re.findall(r'\d+\.\d+', s)
print(numbers) # ['1.23', '4.56']
s = "abc1.23def4.56"
numbers = ''.join(filter(lambda x: x.isdigit() or x == '.', s))
print(numbers) # '1.234.56'