zakaria musa - 1 month ago 4x

Python Question

so i have a problem,i want to take the x number from n digit number

ex:

`number = 9876543210`

i = 4

and return numer[i] # its should return 6

how to do something like that in python. or should i change it to String? and change it again to int for calculation?

Answer

You can do it with integer division and remainder methods

```
def get_digit(number, n):
return number // 10**n % 10
get_digit(987654321, 0)
# 1
get_digit(987654321, 5)
# 6
```

The `//`

does integer division by a power of ten to move the digit to the ones position, then the `%`

gets the remainder after division by 10. Note that the numbering in this scheme uses zero-indexing and starts from the right side of the number.

Source (Stackoverflow)

Comments