为什么这个字典定义会引发语法错误?

时间:2011-10-17 17:53:05

标签: python syntax dictionary

  

可能重复:
  Is there any reason why lVals = [1, 08, 2011] throws an exception?

我正在定义一个字典,用于将日期数字映射到各自的单词。由于某种原因,以下代码引发“SyntaxError:invalid token”并突出显示“08”

days = {01:"first", 02:"second", 03:"third", 04:"fourth", 05:"fifth", 06:"sixth", 07:"seventh", 08:"eighth", 09:"nineth", 10:"tenth", 
    11:"eleventh", 12:"twelvth", 13:"thirteenth", 14:"fourteenth", 15:"fifteenth", 16:"sixteenth", 17:"seventeenth", 18:"eighteenth",
    19:"nineteenth", 20:"twentieth", 21:"twenty-first", 22:"twenty-second", 23:"twenty-third", 24:"twenty-fourth", 25:"twenty-fifth",
    26:"twenty-sixth", 27:"twenty-seventh", 28:"twenty-eighth", 29:"twenty-nineth", 30:"thirtieth", 31:"thirty-first"}

修改代码,使08和09变为98并且99停止任何错误,如下面的代码所示:

days = {01:"first", 02:"second", 03:"third", 04:"fourth", 05:"fifth", 06:"sixth", 07:"seventh", 98:"eighth", 99:"nineth", 10:"tenth", 
    11:"eleventh", 12:"twelvth", 13:"thirteenth", 14:"fourteenth", 15:"fifteenth", 16:"sixteenth", 17:"seventeenth", 18:"eighteenth",
    19:"nineteenth", 20:"twentieth", 21:"twenty-first", 22:"twenty-second", 23:"twenty-third", 24:"twenty-fourth", 25:"twenty-fifth",
    26:"twenty-sixth", 27:"twenty-seventh", 28:"twenty-eighth", 29:"twenty-nineth", 30:"thirtieth", 31:"thirty-first"}

,输出变为:

{1: 'first', 2: 'second', 3: 'third', 4: 'fourth', 5: 'fifth', 6: 'sixth', 7: 'seventh', 10: 'tenth', 11: 'eleventh', 12: 'twelvth', 13: 'thirteenth', 14: 'fourteenth', 15: 'fifteenth', 16: 'sixteenth', 17: 'seventeenth', 18: 'eighteenth', 19: 'nineteenth', 20: 'twentieth', 21: 'twenty-first', 22: 'twenty-second', 23: 'twenty-third', 24: 'twenty-fourth', 25: 'twenty-fifth', 26: 'twenty-sixth', 27: 'twenty-seventh', 28: 'twenty-eighth', 29: 'twenty-nineth', 30: 'thirtieth', 31: 'thirty-first', 98: 'eighth', 99: 'nineth'}

先前错误的键已移至字典的末尾。

非常感谢发现这里发生的事情的人,

詹姆斯

3 个答案:

答案 0 :(得分:9)

数字0是整数文字的前缀,表示它是python中的八进制数。

...我不小心省略了,并且@larsmans在评论中如此友善地指出,将数字限制为只包含数字07,不包括89

虽然,同样值得注意的是,这是Python 2.x中的语法 - 它从Python 3.0开始被更改,表面上是因为你来到这里的确切原因。 PEP 3127包含更改的详细信息。

最相关的一点:

  

几乎所有当前流行的计算机语言,包括C / C ++,Java,Perl和JavaScript,都将前导零的数字序列视为八进制数。将这些数字视为十进制的支持者有一个非常有效的观点 - [...]整个非计算机世界几乎只使用十进制数字。

答案 1 :(得分:1)

在Python中,使用0为数字加前缀表示它是八进制。因此0809会出错,因为八进制中不存在数字89。只需摆脱领先的0,它就会起作用。

答案 2 :(得分:1)

octal中解释以0开头且仅包含数字的数字。 8和9不是有效的八进制数。如果用8和9替换08和09,代码将起作用。