How to pad a numeric string with zeros to the right in Python?

后端 未结 3 1223
借酒劲吻你
借酒劲吻你 2020-12-30 23:34

Python strings have a method called zfill that allows to pad a numeric string with zeros to the left.

In : str(190).zfill(8)
Out: \'00000190\'
<         


        
3条回答
  •  执笔经年
    2020-12-31 00:30

    Hint: The string can be inverted twice: before and after using the zfill method:

    In : acc = '991000'
    
    In : acc[::-1].zfill(9)[::-1]
    Out: '991000000'
    

    Or even more easier:

    In : acc.ljust(9, '0')
    Out: '991000000'
    

提交回复
热议问题