For example, for the program say the house number of hundreds of a number from:
número_int = int(input("Digite um número inteiro: "))
For example, for the program say the house number of hundreds of a number from:
número_int = int(input("Digite um número inteiro: "))
To get the hundredth digit, simply divide the value by 100, take only the integer part of the result, and if there are more digits, get the last digit of the sequence.
>>> numero_int = 5
>>> print(int(str(int(numero_int/100))[-1]))
0
>>> numero_int = 123
>>> print(int(str(int(numero_int/100))[-1]))
1
>>> numero_int = 14589
>>> print(int(str(int(numero_int/100))[-1]))
5
In parts:
int(numero_int/100)
Take the integer part of the result of dividing the number by 100.
str(...)[-1]
Converts the value to string and searches only the last character. This is because if the number is greater than 1000, the integer part of the division by 100 will be greater than 10. For example: int(14589/100)
will be 14, what we want is 4.
int(...)
Converts the last character of the string to int again.
To get the whole part of the division, you can also use the
//
operator, such asnumero_int // 100
, being the equivalent ofint(numero_int / 100)
.
One solution is to divide integer by a power of 10, and use the rest of the division operation by 10. For example, in Python 2 to get the third digit from right to left:
>>> 9912345 / 100 % 10
3
In Python 3 a split between integers returns a float, so you need to use the integer division operator (works in Python 2.7 too):
>>> 9912345 // 100 % 10
3
Transforms to String, then points the location of the number.
num = int(input('Entre com um número de 0 a 9999: '))
n = str(num)
print('\nAnalizando o número {}'.format(n))
print('\nUnidade: {}'
'\nDezena: {}'
'\nCentena: {}'
'\nMilhar: {}'
.format(n[3], n[2], n[1], n[0])
)