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

如何从可能不含数字的字符串提取整数,生成可插入SQL的严格整数值?

简化从字符串提取整数的Python代码

原问题场景

现有一段嵌套列表推导式用于从acc['id_number']中提取整数,代码功能正常但过于冗长:

[int([y or 0 for y in [''.join(re.findall(r'[0-9*]', x))]][0]) for x in [acc['id_number']]][0]

需求明确:

  • 从id_number(取值如'1234'、'na'、'gh1234')中提取所有数字部分
  • 当字符串不含数字时返回0
  • 结果必须是严格整数类型,用于SQL数据库插入

优化方案

方案1:函数封装(可读性优先)

把提取逻辑封装成独立函数,代码更清晰易维护:

import re

def extract_id_number(s):
    # 提取字符串中所有数字字符
    digit_str = ''.join(re.findall(r'\d', s))
    # 有数字则转整数,无数字返回0
    return int(digit_str) if digit_str else 0

替换后的数据生成代码:

raw_accounts = [
    {'account_name': "someone", 'id_number': "2432"},
    {'account_name': "another person", 'id_number': "na"},
    {'account_name': "some other person", 'id_number': "gh134"},
    {'account_name': "another one", 'id_number': "24124"}
]

data = [
    (acc['account_name'], extract_id_number(acc['id_number']))
    for acc in raw_accounts
]

print(data)

输出结果:

[('someone', 2432), ('another person', 0), ('some other person', 134), ('another one', 24124)]

方案2:单行表达式(简洁优先)

如果不想单独定义函数,可直接用更简洁的单行逻辑替代原嵌套推导式:

int(''.join(re.findall(r'\d', acc['id_number'])) or 0)

替换后的数据生成代码:

data = [
    (
        acc['account_name'],
        int(''.join(re.findall(r'\d', acc['id_number'])) or 0)
    ) for acc in raw_accounts
]

利用Python短路逻辑:提取到的数字字符串为空时,'' or 0返回0,再转整数;有数字则直接转整数。


注意事项

  • 原正则[0-9*]包含了*符号,若不需要提取该字符,应改为\d(等价于[0-9]),仅匹配数字
  • 两种方案均返回严格整数类型,满足SQL插入要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 22:15:23