How to take the nth digit of a number in python

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to take the nth digit of a number in python in Python. So Here I am Explain to you all the possible Methods here.

How to take the nth digit of a number in python

1. How to take the nth digit of a number in python?

The // performs integer division by a power of ten to move the digit to the ones position, then the % gets the remainder after division by 10.

2. take the nth digit of a number in python

The // performs integer division by a power of ten to move the digit to the ones position, then the % gets the remainder after division by 10.

Method 1

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 // performs 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.

Method 2

First treat the number like a string

number = 9876543210
number = str(number)

Then to get the first digit:

number

The fourth digit:

number

EDIT:

This will return the digit as a character, not as a number. To convert it back use:

int(number)

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.