如何将尾随零添加到整数 [英] How to add Trailing zeroes to an integer
问题描述
我有一个正整数变量,它的值可以在 0 到 999 之间.然后这个整数被传递给一个软件.
要传入此软件,整数应始终为 3 位.但问题是,它应该有尾随零.
例如:
1 应该作为 100 传递19 应该作为 190 传递255 应该作为 255 传递
可以通过检查变量的长度并根据长度乘以10或100来完成.但是有没有更好的 Python 替代方案.这也不适用于值 0.
(注意:尾随零是因为整数值实际上是一个毫秒值.软件是逐位读取值的,它总是需要3位)
你甚至不需要格式化操作符,只需要简单的 str
方法.用零右对齐:
x.zfill(3)
用零左对齐:
x.ljust(3, '0')
如果 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 always be 3 digits. But the problem is, it should have trailing zeroes. For example: It can be done by checking the length of the variable and multiplying with 10 or 100 depending on the length. But is there any better Python alternative. Also this doesn't work for value 0. (Note: Trailing Zeroes is because the integer value is actually a millisecond value. The software reads the values digit by digit and it always needs 3 digits) You don't even need the formatting operators for this, just plain To left justify with zeroes: You'd need to wrap 这篇关于如何将尾随零添加到整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!x
当前是 int
,则在这种情况下,您需要首先将 x
包装在 str
中.在这一点上,可能值得只使用格式化运算符,因为其他人建议直接生成最终的 str
,当需要证明时.>1 should be passed as 100
19 should be passed as 190
255 should be passed as 255
str
methods. To right justify with zeroes:x.zfill(3)
x.ljust(3, '0')
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.