How to take the nth digit of a number in python

前端 未结 7 1508
梦毁少年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:21

    I would recommend adding a boolean check for the magnitude of the number. I'm converting a high milliseconds value to datetime. I have numbers from 2 to 200,000,200 so 0 is a valid output. The function as @Chris Mueller has it will return 0 even if number is smaller than 10**n.

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

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

    You do have to be careful when checking the boolean state of this return value. To allow 0 as a valid return value, you cannot just use if get_digit:. You have to use if get_digit is False: to keep 0 from behaving as a false value.

提交回复
热议问题