从字符串转换为int时,为什么Python会删除前导零? [英] Why does Python remove leading zeroes when converting from string to int?
本文介绍了从字符串转换为int时,为什么Python会删除前导零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
>>> num = int('0241034812')
>>> print(num)
241034812
>>>
在上面的代码中,我将变量num
设置为0241034812
;但是,当我打印变量时,它会删除第一个零.
In the above code, I'm setting the variable num
to 0241034812
; however, when I print the variable it deletes the first zero.
为什么会这样?
推荐答案
整数存储/显示为普通"数字,而不是字符串值.如果要显示以零开头的数字,则可以在显示变量时执行此操作.
Integers are stored/displayed as a "normal" number, not the string value. If you want to display the number prefixed with zeroes you can do that when displaying the variable.
您可以使用以下语法将前导零添加到整数:
You can use the following syntax to add leading zeros to an integer:
print "%010d" % (241034812,)
上面的示例将显示10c的整数241034812作为0241034812
.
The example above will display the integer 241034812 with 10 digits as 0241034812
.
这篇关于从字符串转换为int时,为什么Python会删除前导零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文