Python实现提取字符串中的数字功能

在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函数将数字拼接成字符串。

猜你喜欢

转载自blog.csdn.net/songpeiying/article/details/132451825