How to pad zeroes to a string?

前端 未结 17 1944
醉酒成梦
醉酒成梦 2020-11-21 22:59

What is a Pythonic way to pad a numeric string with zeroes to the left, i.e. so the numeric string has a specific length?

相关标签:
17条回答
  • 2020-11-21 23:28

    I made a function :

    def PadNumber(number, n_pad, add_prefix=None):
        number_str = str(number)
        paded_number = number_str.zfill(n_pad)
        if add_prefix:
            paded_number = add_prefix+paded_number
        print(paded_number)
    
    PadNumber(99, 4)
    PadNumber(1011, 8, "b'")
    PadNumber('7BEF', 6, "#")
    

    The output :

    0099
    b'00001011
    #007BEF
    
    0 讨论(0)
  • 2020-11-21 23:29

    Just use the rjust method of the string object.

    This example will make a string of 10 characters long, padding as necessary.

    >>> t = 'test'
    >>> t.rjust(10, '0')
    >>> '000000test'
    
    0 讨论(0)
  • 2020-11-21 23:31
    width = 10
    x = 5
    print "%0*d" % (width, x)
    > 0000000005
    

    See the print documentation for all the exciting details!

    Update for Python 3.x (7.5 years later)

    That last line should now be:

    print("%0*d" % (width, x))
    

    I.e. print() is now a function, not a statement. Note that I still prefer the Old School printf() style because, IMNSHO, it reads better, and because, um, I've been using that notation since January, 1980. Something ... old dogs .. something something ... new tricks.

    0 讨论(0)
  • 2020-11-21 23:31

    Another approach would be to use a list comprehension with a condition checking for lengths. Below is a demonstration:

    # input list of strings that we want to prepend zeros
    In [71]: list_of_str = ["101010", "10101010", "11110", "0000"]
    
    # prepend zeros to make each string to length 8, if length of string is less than 8
    In [83]: ["0"*(8-len(s)) + s if len(s) < desired_len else s for s in list_of_str]
    Out[83]: ['00101010', '10101010', '00011110', '00000000']
    
    0 讨论(0)
  • 2020-11-21 23:32
    >>> '99'.zfill(5)
    '00099'
    >>> '99'.rjust(5,'0')
    '00099'
    

    if you want the opposite:

    >>> '99'.ljust(5,'0')
    '99000'
    
    0 讨论(0)
  • 2020-11-21 23:32

    You could also repeat "0", prepend it to str(n) and get the rightmost width slice. Quick and dirty little expression.

    def pad_left(n, width, pad="0"):
        return ((pad * width) + str(n))[-width:]
    
    0 讨论(0)
提交回复
热议问题