Get the Nth digit of a number in Python

avatar

Borislav Hadzhiev

Last updated: Sep 23, 2022

banner

Photo from Unsplash

Get the Nth digit of a number in Python #

To get the Nth digit of a number:

  1. Use the str() class to convert the number to a string.
  2. Access the character at index N - 1.
  3. Use the int() class to convert the result to an integer.
main.py
number = 246810 # ✅ Get Nth digit of a number second = int(str(number)[1]) print(second) # 👉️ 4 third = int(str(number)[2]) print(third) # 👉️ 6 fourth = int(str(number)[3]) print(fourth) # 👉️ 8 # ------------------------------------ # ✅ Get Nth digit of a number from right to left second = int(str(number)[-2]) print(second) # 👉️ 1 third = int(str(number)[-3]) print(third) # 👉️ 8

We used the str() class to convert the integer to a string so we can access the string at a specific index.

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.

Indexes are zero-based, so we have to access the string at index N - 1.

Once we have the Nth digit, we can use the int() class to convert the string to an integer.

main.py
number = 246810 second = int(str(number)[1]) print(second) # 👉️ 4 third = int(str(number)[2]) print(third) # 👉️ 6

You can use negative indices if you need to get the Nth digit of a number from right to left.

main.py
number = 246810 second = int(str(number)[-2]) print(second) # 👉️ 1 third = int(str(number)[-3]) print(third) # 👉️ 8

Negative indices can be used to count backward, e.g. my_str[-1] returns the last character in the string and my_str[-2] returns the second-to-last character.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.