Python Force python to keep leading zeros of int variables

假如想象 提交于 2019-11-27 05:21:25

The concept of leading zeros is a display concept, not a numerical one. You can put an infinite number of leading zeros on a number without changing its value. Since it's not a numeric concept, it's not stored with the number.

You have to decide how many zeros you want when you convert the number to a string. You could keep that number separately if you want.

user9297

Though the comments above are true regarding 1, 01, and 001, are all the same as an INT, it can be very helpful in temporal modeling, or sequential movie making to maintain the leading zeros. I do it often to ensure movie clips are in proper order. The easy way to do that is using zfill. zfill ensures the str version of the number is at least the number of characters you tell it, and does so by filling in the leftside of the string "number" with zeros.

>>> x = int(1)    
>>> NewStringVariable = str(x).zfill(3)    
>>> print NewStringVariable    
001    
>>> NewStringVariable = str(x).zfill(5)    
>>> print NewStringVariable    
00001
julian lewis

I was getting date strings like hhmmss coming across the serial line from my Arduino.

so suppose I got s = "122041"; this would be 12:20:41, however 9am would be 090000.

The statement print "%d" % (s) provokes a run time error because the 9 is not an octal number and is hence an illegal character.

To fix this problem:

print "%06d" % (int(s))

Hope that helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!