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

如何为非补零混合字符串中的数字补零至最长数字位数?

混合字符串数字补零方案

需求:将包含字符与未补零数字的混合字符串中,所有数字补零至所有数字里的最长位数,非数字部分保持原样。

示例

输入:

S70E1
S75E10
S41E100
S53E11
Season1Episode3
Seas3Epi5

输出:

S070E001
S075E010
S041E100
S053E011
Season001Episode003
Seas003Epi005

实现思路(Python)

  1. 从所有输入字符串里提取出所有连续数字,统计出最长的数字位数
  2. 遍历每个字符串,把里面的数字替换成补零到最长位数的版本

代码实现

import re

# 输入数据
input_strings = [
    "S70E1",
    "S75E10",
    "S41E100",
    "S53E11",
    "Season1Episode3",
    "Seas3Epi5"
]

# 提取所有数字,确定最长数字长度
all_digits = re.findall(r'\d+', '\n'.join(input_strings))
max_length = max(len(d) for d in all_digits) if all_digits else 0

# 替换函数:将匹配到的数字补零至max_length位
def pad_match(match):
    return match.group().zfill(max_length)

# 处理每个字符串
result = [re.sub(r'\d+', pad_match, s) for s in input_strings]

# 打印结果
for line in result:
    print(line)

代码说明

  • re.findall(r'\d+', ...):匹配所有连续的数字序列,收集起来用于统计最长长度
  • zfill(max_length):Python字符串方法,自动在数字左侧补零,使其长度达到指定值
  • re.sub(r'\d+', pad_match, s):遍历字符串,把每个数字序列替换成补零后的版本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 22:52:35