为什么此字典定义会引发语法错误?[重复]
问题内容:
这个问题已经在这里有了答案 :
9年前关闭。
我正在定义一个字典,将日期数字映射到它们各自的单词。由于某种原因,以下代码引发“ SyntaxError:无效令牌”并突出显示“ 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'}
先前错误的键已移至字典的末尾。
非常感谢那些发现这里发生的事情的人,
詹姆士
问题答案:
该数字0
是整数文字的前缀,指示它是python中的八进制数字。
…我不小心省略了它,正如@larsmans在他的评论中如此指出的那样,它限制了该数字只能包含0
通过7
,,8
和排除的数字9
。
但是,值得注意的是,这是Python 2.x中的语法-从Python 3.0起它已更改,表面上是由于您来到这里的确切原因。 PEP
3127
包含更改的详细信息。
最相关的位:
几乎所有当前流行的计算机语言,包括C / C
++,Java,Perl和JavaScript,都将带有前导零的数字序列视为八进制数字。支持将这些数字视为小数的支持者有一个非常有效的观点-
整个非计算机领域几乎都使用小数。