Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take the nth digit of a number in python

Tags:

python

int

I want to take the nth digit from an N digit number in python. For example:

number = 9876543210
i = 4
number[i] # should return 6

How can I do something like that in python? Should I change it to string first and then change it to int for the calculation?

like image 313
zakaria musa Avatar asked Sep 22 '16 16:09

zakaria musa


People also ask

How do you find the tens digit in Python?

In Python, you can try this method to print any position of a number. For example, if you want to print the 10 the position of a number, Multiply the number position by 10, it will be 100, Take modulo of the input by 100 and then divide it by 10.


2 Answers

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.

like image 138
Chris Mueller Avatar answered Oct 13 '22 11:10

Chris Mueller


First treat the number like a string

number = 9876543210
number = str(number)

Then to get the first digit:

number[0]

The fourth digit:

number[3]

EDIT:

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

int(number[0])
like image 51
Patrick Haugh Avatar answered Oct 13 '22 09:10

Patrick Haugh