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

前端 未结 6 628
温柔的废话
温柔的废话 2020-12-07 02:28

zipcode = 02132

print zipcode

result = 1114

相关标签:
6条回答
  • 2020-12-07 02:33

    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.

    0 讨论(0)
  • 2020-12-07 02:33

    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.

    0 讨论(0)
  • 2020-12-07 02:52

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

    0 讨论(0)
  • 2020-12-07 02:55

    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.

    0 讨论(0)
  • 2020-12-07 02:56

    The leading 0 makes it assume 02132 is octal.

    0 讨论(0)
  • 2020-12-07 02:56

    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 讨论(0)
提交回复
热议问题