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
相关产品推荐
相关产品推荐

