You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python从字符串中提取正负整数并存储到列表

提取字符串中正负整数的解决方案

你现有的代码仅逐个校验单个字符是否为数字,无法识别多位数和带负号的整数,使用正则匹配可以快速实现需求:

import re

def extractor(string):
    # 匹配可选负号+1位及以上数字的组合
    matched_nums = re.findall(r'-?\d+', string)
    # 将匹配到的字符串转为整数
    int_list = [int(item) for item in matched_nums]
    print(int_list)
    return int_list

效果测试

调用代码传入示例输入:

extractor('hi6 my name is-34 have you seen96?')

输出结果:
[6, -34, 96]
和预期输出完全一致。

内容的提问来源于stack exchange,提问作者Mezza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 09:36:03