可以使用正則表達式或者內置的字符串方法來提取字符串中的數字。
使用正則表達式:
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'