How to add Trailing zeroes to an integer

前端 未结 4 514
失恋的感觉
失恋的感觉 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.

    0 讨论(0)
  • 2021-01-01 06:21

    As mentioned in the question, milliseconds should be 1 -> 001, not 100. One millisecond is a thousandth of a second, not a tenth.

    [str(num).zfill(3) for num in numbers]
    

    or using Tigerhawk's method with the opposite alignment:

    ["{:>03}".format(num) for num in numbers]
    
    0 讨论(0)
  • 2021-01-01 06:24

    I don't know why the zeros got chopped off (ideally you should fix the source of the problem), but you can format the numbers as strings and then turn them back into ints:

    numbers = [1, 19, 255]
    numbers = [int('{:<03}'.format(number)) for number in numbers]
    

    This left-aligns each number with <, in a field 3 characters wide, filling extra characters with 0.

    0 讨论(0)
  • 2021-01-01 06:36

    You can do this by using ljust and str, then casting the result as an int.

    >>> numbers = [1, 19, 255]
    >>> [int(str(num).ljust(3, '0')) for num in numbers]
    [100, 190, 255]
    

    More on ljust here: https://docs.python.org/2/library/stdtypes.html#string-methods

    0 讨论(0)
提交回复
热议问题