可以使用正则表达式或者内置的字符串方法来提取字符串中的数字。
使用正则表达式:
import re
s = "abc123def456"
numbers = re.findall(r'\d+', s)
print(numbers) # ['123', '456']
使用字符串方法:
s = "abc123def456"
numbers = ''.join(filter(str.isdigit, s))
print(numbers) # '123456'
如需提取浮点数,可以稍作修改:
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'