Reputation: 57
I pass float number as string format in int('.0')
0.0 is valid floating point number, so why it is giving error?
Upvotes: 0
Views: 924
Reputation: 71570
You can do it if you remove the quotes and make it a float like:
int(.1)
But strings don't work if inside the string is a float, because they will think it's a number and will break saying '.'
is not a numeric value, also the reason the above works is because:
>>> .1
0.1
>>>
And:
float(0.1)
Works.
Note that even a real float in a string can't be converted into an integer:
>>> int('3.1')
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
int('3.1')
ValueError: invalid literal for int() with base 10: '3.1'
Upvotes: 0
Reputation: 61910
From the documentation of int:
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. Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace.
So it gives you ValueError
because the string '.0'
does not represent an integer literal.
Upvotes: 3
Reputation: 1520
Because you can type cast one step at a time. For example you can convert float to int or string to int. Not a floating point string which here is 2steps.
Upvotes: 2