4

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?

2 Answers 2

15

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I meant in relation to how it's stored in the Memory/Hardware :)
@TapajitDey: The question has nothing to do with how things are stored in memory/hardware. The choice of not allowing implicit conversions of this sort was a deliberate decision by Python's designers.
@TapajitDey Python is a high-level interpreted language, and how it represents data internally is an implementation detail. Why would you rely on it?
I guess that's true, but it just felt kind of limiting
7

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

3 Comments

You sure this is relevant? You're quoting the rules of Python syntax, which don't correspond exactly to what arguments the int function accepts.
@Kos I'm quoting what an integer literal is. int accepts either a number or a string/unicode object that represents an integer literal
As a side note, the lexical analysis docs are an interesting read for people interested in lexers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.