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

Python如何统一列表字符串长度?短字符串补零至15位求助

统一列表字符串为15位长度的解决方案

直接用Python字符串的zfill()方法就能快速解决,这个方法会自动在字符串左侧补零,直到字符串达到指定长度;如果原字符串长度已经等于或超过目标长度,则保持原样。

示例代码

strings = ['110000111100111', '100100110011011', '001101100110', '01011010001110', '111100111001', '1101100111011']
# 遍历列表,对每个字符串执行补零操作
standardized_strings = [s.zfill(15) for s in strings]

print(standardized_strings)

运行结果

['110000111100111', '100100110011011', '000001101100110', '001011010001110', '000111100111001', '011011001110110']

如果需要在右侧补零,可以替换成ljust()方法,写法是s.ljust(15, '0'),按需选择即可。

手动实现逻辑(新手参考)

要是想理解背后的逻辑,也可以手动写循环实现:

standardized_strings = []
target_length = 15
for s in strings:
    length_diff = target_length - len(s)
    if length_diff > 0:
        # 补对应数量的零到字符串左侧
        standardized_strings.append('0' * length_diff + s)
    else:
        standardized_strings.append(s)

这个逻辑就是计算每个字符串和目标长度的差值,差值大于0时补零,否则直接保留原字符串,效果和zfill()完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 06:21:37