In all probability a stupid question, but I was wondering why python can't make a integer out of a string that is actually a float number.
>>> int(1.0)
1
>>> int(float('1.0'))
1
But
>>> int('1.0')
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
int('1.0')
ValueError: invalid literal for int() with base 10: '1.0'
Can anyone clarify why it cant be done in one step?
Can anyone clarify why it cant be done in one step?
To quote the Zen of Python: Explicit is better than implicit.
I was wondering why python can't make a integer out of a string that is actually a float number.
In line with Python's philosophy, if a string contains a float number which you then want to turn into an int, it's your responsibility to spell things out. The language won't try and second-guess your intentions.
Straight from the docs about int
:
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.
And here is how an integer literal in radix base is defined:
longinteger ::= integer ("l" | "L")
integer ::= decimalinteger | octinteger | hexinteger | bininteger
decimalinteger ::= nonzerodigit digit* | "0"
octinteger ::= "0" ("o" | "O") octdigit+ | "0" octdigit+
hexinteger ::= "0" ("x" | "X") hexdigit+
bininteger ::= "0" ("b" | "B") bindigit+
nonzerodigit ::= "1"..."9"
octdigit ::= "0"..."7"
bindigit ::= "0" | "1"
hexdigit ::= digit | "a"..."f" | "A"..."F"
As you can see .
is not present in the lexical definition.
more on int and integer literals
Also worth mentioning that what you wish is naturally achievable in languages of static typing, while Python employs dynamic typing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With