python 中的 int('1.5') VS float('1.5')
int('1.5') VS float('1.5') in python
为什么 float('1.5')
按预期输出 1.5
但 int('1.5')
给出值错误?
不应该python自动将字符串转换为浮点数然后再转换为整数。
因为 1.5
不是 int()
函数所需的有效整数文字。
来自docs:
If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in radix
base.
而整数文字定义如下:
integer ::= decinteger | bininteger | octinteger | hexinteger
decinteger ::= nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")*
bininteger ::= "0" ("b" | "B") (["_"] bindigit)+
octinteger ::= "0" ("o" | "O") (["_"] octdigit)+
hexinteger ::= "0" ("x" | "X") (["_"] hexdigit)+
nonzerodigit ::= "1"..."9"
digit ::= "0"..."9"
bindigit ::= "0" | "1"
octdigit ::= "0"..."7"
hexdigit ::= digit | "a"..."f" | "A"..."F"
来源:https://docs.python.org/3/reference/lexical_analysis.html#integers
为什么 float('1.5')
按预期输出 1.5
但 int('1.5')
给出值错误?
不应该python自动将字符串转换为浮点数然后再转换为整数。
因为 1.5
不是 int()
函数所需的有效整数文字。
来自docs:
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base.
而整数文字定义如下:
integer ::= decinteger | bininteger | octinteger | hexinteger
decinteger ::= nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")*
bininteger ::= "0" ("b" | "B") (["_"] bindigit)+
octinteger ::= "0" ("o" | "O") (["_"] octdigit)+
hexinteger ::= "0" ("x" | "X") (["_"] hexdigit)+
nonzerodigit ::= "1"..."9"
digit ::= "0"..."9"
bindigit ::= "0" | "1"
octdigit ::= "0"..."7"
hexdigit ::= digit | "a"..."f" | "A"..."F"
来源:https://docs.python.org/3/reference/lexical_analysis.html#integers