How to pad zeroes to a string?

前端 未结 17 1940
醉酒成梦
醉酒成梦 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
    

提交回复
热议问题