
python中如何在字符串中提取整数
用户关注问题
我有一个包含数字和字母的字符串,想从中提取所有整数数字,应该用什么方法?
利用正则表达式提取整数
可以使用Python的re模块,通过正则表达式模式'\d+'从字符串中提取所有连续的数字序列。这些数字序列可以表示整数。示例代码如下:
import re
s = 'abc123def45gh6'
numbers = re.findall(r'\d+', s)
integers = [int(num) for num in numbers]
print(integers) # 输出: [123, 45, 6]
如果字符串里只想提取第一个出现的整数,应该怎样做?
使用re.search捕获单个整数
使用re.search配合正则表达式'\d+'可以找到字符串中第一个匹配的数字序列。通过.group()方法获得匹配的字符串并转成整数即可。示例代码:
import re
s = 'order number 2023 received'
match = re.search(r'\d+', s)
if match:
first_integer = int(match.group())
print(first_integer) # 输出: 2023
else:
print('未找到整数')
假设字符串中含有正负整数,怎样才能同时提取包括负号的整数?
正则表达式匹配带负号的整数
可以使用正则表达式'-?\d+'匹配整数,其中'-?'表示负号可有可无。通过re.findall获取所有匹配项,再转换为整数即可。示例代码:
import re
s = '温度为-5度,最高温度是12度'
numbers = re.findall(r'-?\d+', s)
integers = [int(num) for num in numbers]
print(integers) # 输出: [-5, 12]