2010-12-19 165 views
3
>>> n = ''.join(i for i in x if i.isdigit()) 
>>> n.isdigit() 
True 
>>> x.isdigit() 
False 

>>> previous = 0 
>>> next = 100 
>>> answer = 0 


>>> for i in range(0,100): 
...  answer += int(n[previous:next]) 
...  previous = next 
...  next += 100 
... 
Traceback (most recent call last): 
    File "<stdin>", line 2, in <module> 
ValueError: invalid literal for int() with base 10: '' 

爲什麼我會收到此錯誤?正如你所看到的n是數字..對於基數爲10的int,文字無效:''

回答

7

n可能是數字,但在某個階段,你會超過n的長度,使得n[previous:next]根本不包含任何字符。空字符串''不能轉換爲int,因此錯誤會告訴整個故事:invalid literal for int() with base 10: ''

>>> int('') 
Traceback (most recent call last): 
    File "<input>", line 1, in <module> 
ValueError: invalid literal for int() with base 10: '' 
+0

那麼,你我可以看到我已經從字符串去除一切,但數字N =「」。加入(在X I爲我如果i.isdigit()),沒有這個做的工作? – Marijus 2010-12-19 19:51:02

+0

@Marijus刪除非數字不會阻止您獲取空字符串。一個空字符串包含「僅數字」,但仍不是整數。 – marcog 2010-12-19 19:52:53

+0

這就是我使用answer + = int(n [previous:next])的原因 – Marijus 2010-12-19 19:57:19

相關問題