How to take the nth digit of a number in python

前端 未结 7 1461
梦毁少年i
梦毁少年i 2020-11-30 10:42

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

7条回答
  •  有刺的猬
    2020-11-30 11:13

    Here's my take on this problem.

    I have defined a function 'index' which takes the number and the input index and outputs the digit at the desired index.

    The enumerate method operates on the strings, therefore the number is first converted to a string. Since the indexing in Python starts from zero, but the desired functionality requires it to start with 1, therefore a 1 is placed in the enumerate function to indicate the start of the counter.

    def index(number, i):
    
        for p,num in enumerate(str(number),1):
    
            if p == i:
                print(num)
    

提交回复
热议问题