How can we extract numbers from a string in Python?
There are several ways to extract the numbers from a string.
- Regular expressions can be used to match numbers within a string by using the findall function in the re module. For example:
import re
string = "abc123def456"
numbers = re.findall(r'\d+', string)
print(numbers) # 输出:['123', '456']
- By using the isdigit() method, you can iterate through each character in a string and determine if it is a digit. For example:
string = "abc123def456"
numbers = ''.join([char for char in string if char.isdigit()])
print(numbers) # 输出:123456
- By using the isnumeric() method, similar to isdigit(), it is able to also determine if it contains other numerical characters (such as Chinese numerals). For example:
string = "abc一二三def四五六"
numbers = ''.join([char for char in string if char.isnumeric()])
print(numbers) # 输出:一二三四五六
Please note that the extracted numbers in the above methods will be returned as strings. If you need to convert them into integers or floating-point numbers, you can use the int() or float() functions for type conversion.