How to add Trailing zeroes to an integer

前端 未结 4 516
失恋的感觉
失恋的感觉 2021-01-01 05:57

I have a positive integer variable which can have values between 0 to 999. This integer is then passed to a software.

To pass into this software the integer should a

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-01 06:21

    You don't even need the formatting operators for this, just plain str methods. To right justify with zeroes:

    x.zfill(3)
    

    To left justify with zeroes:

    x.ljust(3, '0')
    

    You'd need to wrap x in str first in this scenario if x is currently an int. At that point, it may be worth just using the formatting operators as others have suggested to directly produce the final str, with no intermediate str, when justification is required.

提交回复
热议问题