Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
先頭にゼロを付けて整数を変数に格納すると、Python が奇妙な動作をするのはなぜですか? 1つはエラーを出し、もう1つは値を間違って保存しますか?
>>> zipcode = 02492 SyntaxError: invalid token >>> zipcode = 02132 >>> zipcode 1114
0 で始まる数値は8 進数として解釈されます。
In [32]: oct(1114) Out[32]: '02132' In [33]: int('2132', 8) Out[33]: 1114 In [34]: 02132 == 1114 Out[34]: True
Python3では、8 進リテラルはの代わりに0oorを先頭に指定する必要があることに注意してください。0O0
0o
0O
0
int先行ゼロのリテラルは 8 進数として解釈され9、有効な数値ではありません。範囲内の数字で形成された数値のみ[0, 7]が有効な 8 進数です。
int
9
[0, 7]