【问题标题】:Why does this dictionary definition raise a syntax error? [duplicate]为什么这个字典定义会引发语法错误? [复制]
【发布时间】:2011-10-17 17:53:04
【问题描述】:

可能重复:
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'}

以前错误的键已移到字典的末尾。

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

詹姆斯

【问题讨论】:

    标签: python syntax dictionary


    【解决方案1】:

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

    ...正如我不小心遗漏的那样,正如@larsmans 在他的评论中如此亲切地指出的那样,将数字限制为仅包含数字07,不包括89

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

    最相关的位:

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

    【讨论】:

    • ... 显然,08 不是有效的八进制数。 +1。
    【解决方案2】:

    在 Python 中,以 0 为前缀的数字表示它是八进制的。所以0809 给出错误,因为数字89 在八进制中不存在。只要去掉前面的0 就可以了。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多