How to take the nth digit of a number in python

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

    I'm very sorry for necro-threading but I wanted to provide a solution without converting the integer to a string. Also I wanted to work with more computer-like thinking so that's why the answer from Chris Mueller wasn't good enough for me.

    So without further ado,

    import math
    
    def count_number(number):
        counter = 0
        counter_number = number
        while counter_number > 0:
            counter_number //= 10
            counter += 1
        return counter
    
    
    def digit_selector(number, selected_digit, total):
        total_counter = total
        calculated_select = total_counter - selected_digit
        number_selected = int(number / math.pow(10, calculated_select))
        while number_selected > 10:
            number_selected -= 10
        return number_selected
    
    
    def main():
        x = 1548731588
        total_digits = count_number(x)
        digit_2 = digit_selector(x, 2, total_digits)
        return print(digit_2)
    
    
    if __name__ == '__main__':
        main()
    

    which will print:

    5
    

    Hopefully someone else might need this specific kind of code. Would love to have feedback on this aswell!

    This should find any digit in a integer.

    Flaws:

    Works pretty ok but if you use this for long numbers then it'll take more and more time. I think that it would be possible to see if there are multiple thousands etc and then substract those from number_selected but that's maybe for another time ;)

    Usage:

    You need every line from 1-21. Then you can call first count_number to make it count your integer.

    x = 1548731588
    total_digits = count_number(x)
    

    Then read/use the digit_selector function as follows:

    digit_selector('insert your integer here', 'which digit do you want to have? (starting from the most left digit as 1)', 'How many digits are there in total?')

    If we have 1234567890, and we need 4 selected, that is the 4th digit counting from left so we type '4'.

    We know how many digits there are due to using total_digits. So that's pretty easy.

    Hope that explains everything!

    Han

    PS: Special thanks for CodeVsColor for providing the count_number function. I used this link: https://www.codevscolor.com/count-number-digits-number-python to help me make the digit_selector work.

    0 讨论(0)
提交回复
热议问题