Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python int() of a string that is a float number

Tags:

python

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?

like image 582
Tapajit Dey Avatar asked Nov 30 '22 01:11

Tapajit Dey


2 Answers

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.

like image 104
NPE Avatar answered Dec 05 '22 11:12

NPE


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

like image 26
dmg Avatar answered Dec 05 '22 13:12

dmg