How to take the nth digit of a number in python

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

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

How can I do something like this in python? Should I change it to a string first and then change it to int to compute?

+13
source share
4 answers

First process the number as a string

 number = 9876543210 number = str(number) 

Then, to get the first digit:

 number[0] 

Fourth digit:

 number[3] 

EDIT:

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

 int(number[0]) 
+13
source

You can do this using integer division and break methods

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

// performs an integer division by 10 units to translate the digit into one position, then % gets the remainder after dividing by 10. Note that the numbering in this scheme uses zero indexing and starts on the right side of the number.

+34
source

Ok, first, use the str () function in python to turn a "number" into a string

 number = 9876543210 #declaring and assigning number = str(number) #converting 

Then get the index, 0 = 1, 4 = 3 in the index notation, use int () to turn it into a number

 print(int(number[3])) #printing the int format of the string "number" index of 3 or '6' 

if you like in short form

 print(int(str(9876543210)[3])) #condensed code lol, also no more variable 'number' 
0
source

I would recommend adding a Boolean check for the value of the number. I convert a large value in milliseconds to a date and time. I have numbers from 2 to 200, 000, 200, so 0 is the correct conclusion. The function @Chris Mueller has will return 0, even if the number is less than 10 ** n.

 def get_digit(number, n): return number // 10**n % 10 get_digit(4231, 5) # 6 

 def get_digit(number, n): if number - 10**n < 0: return False return number // 10**n % 10 get_digit(4321, 5) # False 

You must be careful when checking the logical state of this return value. To allow 0 as a valid return value, you cannot just use if get_digit: you must use if get_digit is False: so that 0 acts as a false value.

0
source

All Articles