How to get digits of a number in python

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.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given a number and the task is to find sum of digits of this number in Python. 
    Examples: 
     

    Input : n = 87 
    Output : 15 
    Input : n = 111 
    Output : 3

     
    Below are the methods to sum of the digits. 
    Method-1: Using str() and int() methods.: The str() method is used to convert the number to string. The int() method is used to convert the string digit to an integer. 

    Convert the number to string and iterate over each digit in the string and after converting each digit to integer and add to the sum of the digits in each iteration. 

    Python3

    def getSum(n):

        sum = 0

        for digit in str(n): 

          sum += int(digit)      

        return sum

    n = 12345

    print(getSum(n))

    Output:

    15

    Method-2: Using sum() methods.: The sum() method is used to sum of numbers in the list.

    Convert the number to string using str() and strip the string and convert to list of number using strip() and map() method resp. Then find the sum using the sum() method.

    Python3

    def getSum(n):

        strr = str(n)

        list_of_number = list(map(int, strr.strip()))

        return sum(list_of_number)

    n = 12345

    print(getSum(n))

    Output:

    15

    Method-3: Using General Approach: 

    • Get the number
    • Declare a variable to store the sum and set it to 0
    • Repeat the next two steps till the number is not 0
    • Get the rightmost digit of the number with help of remainder ‘%’ operator by dividing it with 10 and add it to sum.
    • Divide the number by 10 with help of ‘//’ operator
    • Print or return the sum

    A. Iterative Approach:

    Python3

    def getSum(n):

        sum = 0

        while (n != 0):

            sum = sum + (n % 10)

            n = n//10

        return sum

    n = 12345

    print(getSum(n))

    Output:

    15

    B. Recursive Approach:

    Python3

    def sumDigits(no):

        return 0 if no == 0 else int(no % 10) + sumDigits(int(no / 10)) 

    n = 12345

    print(sumDigits(n))

    Output:

    15

    How do you find the digits of a number in Python?

    int(str(number)[i-1]) . Or if you need to handle all digits: for index, digit in enumerate(str(number), start=1): digit = int(digit) ... .
    Stack Overflow is not a code-writing or tutorial service..

    How do you extract digits of a number?

    Extracting digits of a number is very simple. When you divide a number by 10, the remainder is the digit in the unit's place. You got your digit, now if you perform integer division on the number by 10, it will truncate the number by removing the digit you just extracted.

    How do you split a number into digits in Python?

    To split an integer into digits: Use the str() class to convert the integer to a string. Use a list comprehension to iterate over the string. On each iteration, use the int() class to convert each substring to an integer.

    How do I print an individual digit of a number in Python?

    “get individual digits from int python” Code Answer's.
    >>> n = 43365644..
    >>> digits = [int(x) for x in str(n)].
    >>> digits..
    >>> lst. extend(digits) # use the extends method if you want to add the list to another..