問題描述
正如標題所說,在 Python 中(我在 2.7 和 3.3.2 中嘗試過),為什么 int('0.0')
不起作用?它給出了這個錯誤:
As the title says, in Python (I tried in 2.7 and 3.3.2), why int('0.0')
does not work? It gives this error:
ValueError: invalid literal for int() with base 10: '0.0'
如果您嘗試 int('0')
或 int(eval('0.0'))
它會起作用...
If you try int('0')
or int(eval('0.0'))
it works...
推薦答案
只是因為 0.0
不是以 10 為底的有效整數.而 0
是.
Simply because 0.0
is not a valid integer of base 10. While 0
is.
閱讀 int()
這里.一個>
int(x, base=10)
int(x, base=10)
將數字或字符串 x 轉換為整數,或返回如果沒有給出參數,則為 0.如果 x 是一個數字,它可以是一個普通的整數、長整數或浮點數.如果 x 是浮動的點,轉換截斷為零.如果論據是在整數范圍之外,函數返回一個長對象.
Convert a number or string x to an integer, or return 0 if no arguments are given. If x is a number, it can be a plain integer, a long integer, or a floating point number. If x is floating point, the conversion truncates towards zero. If the argument is outside the integer range, the function returns a long object instead.
如果 x 不是一個數字或者如果給出了基數,那么 x 必須是一個字符串或者Unicode 對象,表示以基數為基礎的整數文字.可選地,文字可以在前面加上 + 或 - (中間沒有空格之間)并被空格包圍.一個 base-n 文字由數字 0 到 n-1,其中 a 到 z(或 A 到 Z)的值是 10 到 35.默認基數為 10.允許的值為 0 和 2-36.基數 2,-8,和 -16 字面值可以選擇以 0b/0B、0o/0O/0 或0x/0X,與代碼中的整數文字一樣.Base 0 表示解釋字符串與整數文字完全一樣,因此實際基數為 2、8、10 或 16.
If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in radix base. Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35. The default base is 10. The allowed values are 0 and 2-36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O/0, or 0x/0X, as with integer literals in code. Base 0 means to interpret the string exactly as an integer literal, so that the actual base is 2, 8, 10, or 16.
這篇關于Python 2.7 和 3.3.2,為什么 int('0.0') 不起作用?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!