How to get every digit 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: //www.codevscolor.com/count-number-digits-number-python to help me make the digit_selector work.

  1. HowTo
  2. Python How-To's
  3. Split Integer Into Digits in Python

Created: May-26, 2021

  1. Use List Comprehension to Split an Integer Into Digits in Python
  2. Use the math.ceil[] and math.log[] Functions to Split an Integer Into Digits in Python
  3. Use the map[] and str.split[] Functions to Split an Integer Into Digits in Python
  4. Use a for Loop to Split an Integer Into Digits in Python

This tutorial will discuss different methods to split an integer into digits in Python.

Use List Comprehension to Split an Integer Into Digits in Python

List comprehension is a much shorter and graceful way to create lists that are to be formed based on given values of an already existing list.

In this method, str[] and int[] functions are also used along with List comprehension to split the integer into digits. str[] and int[] functions are used to convert a number to a string and then to an integer respectively.

The following code uses list comprehension to split an integer into digits in Python.

num = 13579
x = [int[a] for a in str[num]]
print[x]

Output:

[1, 3, 5, 7, 9]

The number num is first converted into a string using str[] in the above code. Then, list comprehension is used, which breaks the string into discrete digits. Finally, the digits are converted back to an integer using the int[] function.

Use the math.ceil[] and math.log[] Functions to Split an Integer Into Digits in Python

The operation of splitting the integer into digits in Python can be performed without converting the number to string first. Moreover, this method is about twice as fast as converting it to a string first.

The math.ceil[] function rounds off a number up to an integer. The math.log[] function provides the natural logarithm of a number. To use both these functions, we should import the math library.

The math module can be defined as an always accessible and standard module in Python. It provides access to the fundamental C library functions.

The following code uses list comprehension, math.ceil[] and math.log[] functions to split an integer into digits in Python.

import math
n = 13579
x = [[n//[10**i]]%10 for i in range[math.ceil[math.log[n, 10]]-1, -1, -1]]
print[x]

Output:

[1, 3, 5, 7, 9]

Use the map[] and str.split[] Functions to Split an Integer Into Digits in Python

The map[] function implements a stated function for every item in an iterable. The item is then consigned as a parameter to the function.

The split[] method, as the name suggests, is used to split a string into a list. It has a basic syntax and holds two parameters, separator, and the maxsplit.

The number needs to be already in the string format so that this method could be used.

The following code uses the map[] and str.split[] functions to split an integer into digits in Python.

str1 = "1 3 5 7 9"
list1 = str1.split[]
map_object = map[int, list1]

listofint = list[map_object]
print[listofint]

Output:

[1, 3, 5, 7, 9]

Here, we used the str.split[] method to split the given number in string format into a list of strings containing every number. Then the map[] function is used, which is utilized to generate a map object which converts each string into an integer. Finally, list[mapping] is used to create a list from the map object.

Use a for Loop to Split an Integer Into Digits in Python

In this method, we use a loop and perform the slicing technique till the specified number of digits [A=1 in this case] and then finally, use the int[] function for conversion into an integer.

The following code uses the int[]+loop+slice to split an integer into digits in Python.

str1 = '13579'
# initializing substring
A = 1
# create a result list
result = []
for i in range[0, len[str1], A]:
    # convert to int, after the slicing process
    result.append[int[str1[i : i + A]]]
  
print["The resultant list : " + str[result]]

Output:

The resultant list : [1, 3, 5, 7, 9]

Related Article - Python Integer

  • Convert Int to Binary in Python
  • Integer Programming in Python
  • Convert Boolean Values to Integer in Python
  • Convert String to Integer in Python

    Related Article - Python String

  • Convert Int to Binary in Python
  • Integer Programming in Python
  • Convert Boolean Values to Integer in Python
  • Convert String to Integer in Python
  • How do I extract all digits from 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 iterate through a digit in a number in Python?

    Method 1: Iterate through digits of a number in python using the iter[] function. The first method to iterate through digits of a number is the use of iter[] function. It accepts the string value as the argument. Therefore you have to first typecast the integer value and then pass it into it.

    Chủ Đề