Even if he type 1
or 1.0
will be string
anyway, a string
can be numerically formatted normally, just because 1
is a number doesn’t mean his type will be int
.
What you can do is use two regex to detect which format the string resembles and then do the cast, for example:
import re
entrada = input()
if re.match('^\d+$', entrada):
entrada = int(entrada)
elif re.match('^\d+\.\d+$', entrada):
entrada = float(entrada)
print(type(entrada), entrada)
A regex ^\d+$
of the first if
will search from start to end of string if it has number format, no point.
A regex ^\d+\.\d+$
of the first if
will search from the beginning to the end of the string starting with numeric format until it reaches a point, as soon as it reaches the point will look for the number after it, if it occurs the match
will enter the if
Should you not recognize any he will print as string
even
About Python 2.7
Just for the record, in Python version 2.7 input()
evaluated the content on its own (as if "val"), so if you did a script like this:
entrada = input()
print type(entrada), entrada
When the input was 1
would return: <type 'int'> 1
When the input was 1.0
would return: <type 'float'> 1.0
When the input was "1"
would return: <type 'str'> "1"
So the equivalent of input()
of Python 3 to the Python 2 actually would be the raw_input()
But I think this was not the question. As I said, if the return will always be string, the condition
isinstance(valor, int)
at all times will be false, so it makes no sense to use it. And if you use theint
to convert, will fall in Maniero’s answer: if the program knows the type, have no reason to check. Then his reply was very confused and I could not understand what he meant. By the way, comments inline in Python is used#
, nay//
.– Woss
All the user types is string, however, I can convert a string "1" to int, but I can’t convert an str "a" to int. Although everything is string, not everything can be converted, understand? It can for example try to convert the input and then check if the conversion occurred correctly and isinstance() is a great way to do this. Used with Try except then, it would solve the problem. But I just wanted to add something. Most have written several lines to do the same thing as the function. As for the comments I am aware, but wanted to represent the debug if you did not understand.
– Danilo Sampaio