开发者

Not getting exact result in python with the values leading zero. Please tell me what is going on there

开发者_如何学Go

zipcode = 02132

print zipcode

result = 1114


A leading zero means octal. 2132 in octal equals 1114 in decimal. They removed this behavior in Python 3.0.


In Python 2.x, number with a leading zero is interpreted as octal (base-eight). Python 3.x requires a leading "0o" to indicate an octal number. You probably want to treat a zipcode as a string to keep the leading zeroes intact.


Quite apart from the octal caper:

Zip codes, social security "numbers", credit card "numbers", phone "numbers", etc are NOT numbers in the sense that you can do meaningful arithmetic on them, so don't keep them as integers, keep them as strings.


The leading 0 makes it assume 02132 is octal.


leading zero means octal as other have said. one way to keep your zero is to strip the leading zeros and just use a zero padded string when you display it,


>>> myInt = 2132
>>> print myInt
2132
>>> myString = "%05d" % myInt
>>> print myString
02132
>>> print int(myString)
2132

you probably get the idea.


What is your question? I guess, why is that. The answer is octal numbers. If a number starts with a zero, Python thinks you mean an octal number. (Base 8)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜