Even if he types 1
or 1.0
will string
anyway, string
can be numeric format normally, just because 1
is a number does not mean that his type will be int
.
What you can do is to use two regex to detect which format the string resembles and then 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)
The regex ^\d+$
of the first if
will search from the beginning to the end of the string if it is numeric, without a dot.
The% regex% of the first ^\d+\.\d+$
will search from beginning to end of the string starting with numeric format until it reaches a point, once it reaches the point it will look for the number after it, if% will enter the if
Do not recognize any it will print as if
same
About Python 2.7
Just to note, in Python version 2.7 the match
would evaluate the content on its own (as if it were rolling "eval" ), then a script like this would be done:
entrada = input()
print type(entrada), entrada
-
When the input was string
would return: input()
-
When the input was 1
would return: <type 'int'> 1
-
When the input was 1.0
would return: <type 'float'> 1.0
Then the equivalent of Python 3 "1"
/ em> for Python 2 would actually be <type 'str'> "1"