How to convert int variable to string without eliminating zeros?
I need to perform in an activity the validation of the characters entered by the user.
My Code:
mes1 = int (input ('Digite o mês inicial:'))
valida = len (str (mes1))
while valida != 2:
print ('Valor inválido! O mês deve ter 2 dígitos.')
mes1 = int (input ('Digite o mês inicial:'))
valida = len (str (mes1))
The problem is that when I convert int to string in the "validate" variable, the zeros are disregarded. Ex: I enter month 12, all correct; I enter month 02, error.
Error Image:
3 answers
An integer value has no zeros left; if you need to keep them you should keep their value as string, but if the intention is to do this to validate a month, don't. Month 02 is the same as month 2, so validating if it has two characters is not enough validation (42 is a valid month? It has two characters).
If you want to validate if a number has been entered and if it is a valid month you will need to handle the exception ValueError
which is thrown by int
when the value does not is numeric and to know if it is a valid value for the month just check if it is between 1 and 12 inclusives. Theoretically if I report "Month 2 "or" month 02 " should be the same thing, then it cannot validate if there are two characters.
while True:
try:
month = int(input('Mês: '))
if 1 <= month <= 12:
break
print('Informe um valor entre 1 e 12')
except ValueError:
print('Informe um valor numérico')
When running you would have an output like:
>>> Mês: a
Informe um valor numérico
>>> Mês: 13
>>> Informe um valor entre 1 e 12
Mês: 5
See working on Repl.it
Important Note: a string with zero the left is completely different from a value with zero a left. In Python 2 the zero left in an integer was used to indicate that the value was octal, that is, base 8 and not base 10. Doing, for example, print(010)
in Python 2 will display 8, since the number 010 in base 8 equals the number 8 in base 10. In Python 3 this notation was changed to 0o10
, with the letter o
between the values and started to generate a syntax error for integers with 0 on the left. Be very careful not to confuse things.
Is simple, do not convert to integer, if you already have the information the way you want, then use it straight. If you need the conversion, do it after validating. In the end I made the conversion if you still need it, I do not know if you really need it, it may be a conceptual mistake there.
Took advantage and removed the redundancy of the code, now the request appears once, respecting the DRY . I improved the organization of the code.
while True:
mes = input('Digite o mês inicial:')
if len(mes) == 2:
break;
print ('Valor inválido! O mês deve ter 2 dígitos.')
mes1 = int(mes)
print(mes1)
See working on ideone. And no repl.it. also I put on GitHub for future reference .
Face there is no integer with 0 on the left side 01 = = 1, then reads the input as string and makes string comparison.