在Python中提取字符串中的数字可以使用正则表达式或者字符串处理函数。
使用正则表达式实现:
import re
s = 'Hello 12345 World'
nums = re.findall(r'\d+', s)
print(nums) # ['12345']
这里使用re
模块的findall
函数,使用正则表达式\d+
匹配字符串中的数字,返回结果即为列表形式的数字。
使用字符串处理函数实现:
s = 'Hello 12345 World'
nums = ''.join(filter(str.isdigit, s))
print(nums) # '12345'
这里使用filter
函数过滤出字符串中的数字,然后使用join
函数将数字拼接成字符串。