【问题标题】:Padding with zeros in the middle of a string?在字符串中间用零填充?
【发布时间】:2016-12-08 00:53:55
【问题描述】:

已回答here 用前导零填充数字。但就我而言,我有一个字符串字符后跟数字。我想在字符串字符之后、数字之前添加前导零,使总长度保持为 4。例如:

A1 -> A001
A12 -> A012
A123 -> A123

我有下面的代码可以得到我想要的,但是有没有更短的方法来做到这一点,而无需先使用 re 将我的字符串拆分为文本和数字?

import re
mystr = 'A4'
elements = re.match(r"([a-z]+)([0-9]+)", mystr, re.I)
first, second = elements.groups()
print(first + '{:0>3}'.format(second))

output = A004

【问题讨论】:

    标签: python-3.x text format


    【解决方案1】:

    您可以使用以下内容来避免使用re:

    def pad_center(s):
        zeros = '0' * (4 - len(s))
        first, *the_rest = list(s)
        return first + zeros + ''.join(the_rest)
    
    print(pad_center('A1'))
    print(pad_center('A12'))
    print(pad_center('A123'))
    

    或者,如果你想使用format(),你可以试试这个:

    def pad_center(s):
        zeros = '0' * (4 - len(s))
        first, *the_rest = list(s)
        return '{}{}{}'.format(first, zeros, ''.join(the_rest))
    

    但是,我不知道有任何方法可以在没有事先处理的情况下使用format string syntax 在字符串的中心添加填充。

    【讨论】:

    • @Murchak 抱歉,我不知道,但请参阅我的更新答案。
    猜你喜欢
    • 2011-05-27
    • 2018-11-14
    • 2010-09-24
    • 2020-03-16
    • 2019-11-21
    • 2012-02-17
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多