How can I get the nth digit of a number when the first digit is on the right-most of the number? I'm doing this on python.
Asked
Active
Viewed 6,376 times
0
-
Can you post some code of what you have tried so far? Do you have some example inputs / outputs? – Cameron Downer Aug 28 '18 at 15:58
-
Let's say the number is 1234.567. What is its 4th digit? Or is the number guaranteed to be an integer? – Kevin Aug 28 '18 at 15:58
-
1You can get the logic from [here](https://stackoverflow.com/questions/39644638/how-to-take-the-nth-digit-of-a-number-in-python) which is about nth digit from left. You can modify the same for your case. – dodobhoot Aug 28 '18 at 16:04
-
Although the duplicate is asking how to count from the left rather than the right, the second answer is actually counting from the right, and the accepted one can count from either side (it’s just a matter of negative indexing), so I think your best answers are all there. – abarnert Aug 28 '18 at 16:14
5 Answers
2
You could convert the number to a string and then use a negative index to access a specific digit from the end:
>>> num = 123456
>>> n = 3
>>> str(num)[-n]
'4'

Mureinik
- 297,002
- 52
- 306
- 350
-
How would this deal with 123.456? should we clean out special characters? – Roy Shahaf Aug 28 '18 at 16:03
-
Depends on what the OP's requirement is. If you just want to skip over it you could just filter it out. – Mureinik Aug 28 '18 at 16:04
1
If your numbers are integers, you can compute it with integer division and modulo:
def nth_digit(number, digit):
return abs(number) // (10**(digit-1)) % 10
nth_digit(4321, 1)
# 1
nth_digit(4321, 2)
# 2
If we go further left, the digit should be 0:
nth_digit(4321, 10)
# 0

Thierry Lathuille
- 23,663
- 10
- 44
- 50
-
-
-
@PatrickHaugh, RoyShahaf: That's right, I had a bit too quickly assumed I was dealing with positive integers. Corrected! – Thierry Lathuille Aug 28 '18 at 16:05
0
Here's one way, assuming you are talking about integers and the decimal system:
def extract_digit(n, number):
number = abs(number)
for x in range(n-1):
number = number // 10 #integer division, removes the last digit
return number % 10

Mr. Eivind
- 199
- 2
- 11
0
Convert to a string, reverse the string, and then take the index of the string and convert the string back into an integer. This works:
def nth_digit(digit, n):
digit = str(digit)
return int(digit[::-1][n])
Let me know if this works for you!

CodeRocks
- 655
- 5
- 10
- 25
-2
Convert to a string, reverse the string, and then take the index of the string and convert the string back into an integer. This works:
def nth_digit(digit, n):
digit = str(digit)
return int(digit[::-1][n])
Let me know if this works for you!

CodeRocks
- 655
- 5
- 10
- 25
-
If they just wanted the rightmost digit, they could just `%10`. They asked for the nth digit. – mypetlion Aug 28 '18 at 16:03