2011-10-17 66 views
1

Possible Duplicate:
Is there any reason why lVals = [1, 08, 2011] throws an exception?爲什麼這個字典定義會引發語法錯誤?

我正在定義一個字典來將天數映射到它們各自的單詞。出於某種原因,下面的代碼提出了「語法錯誤:無效令牌」,並強調「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'} 

先前錯誤鍵已移動到詞典的末尾。

非常感謝誰斑是怎麼回事的人,

詹姆斯

回答

9

人數0是表明它是在Python一個八進制數字面整數的前綴。

...其作爲我意外地省略,並且如在@larsmans他的評論如此麻煩指出的那樣,限制了編號,以僅通過07含有標記,不含89

雖然,也值得注意的是,這是Python 2.x中的語法 - 從Python 3.0開始已經發生了變化,表面上出於您來到這裏的確切原因。 PEP 3127包含更改的詳細信息。

最相關的位:

Almost all currently popular computer languages, including C/C++, Java, Perl, and JavaScript, treat a sequence of digits with a leading zero as an octal number. Proponents of treating these numbers as decimal instead have a very valid point -- [...] the entire non-computer world uses decimal numbers almost exclusively.

+0

...顯然,'08'不是有效的八進制數。 +1。 –

1

在Python,前綴一個數字與0表示它爲八進制。所以0809給出錯誤,因爲數字89不存在八進制。只要擺脫領先0,它會工作。

1

從0開始並且只包含數字的數字在octal中解釋。 8和9不是有效的八進制數字。如果用8和9代替08和09,代碼將起作用。

相關問題