In Python, there are a number of ways we can split a number into digits. The easiest way to get the digits of an integer is to use list comprehension to convert the number into a string and get each element of the string.
def getDigits(num):
return [int(x) for x in str(num)]
print(getDigits(100))
print(getDigits(213))
#Output:
[1,0,0]
[2,1,3]
We can also get the digits of a number using a for loop in Python.
def getDigits(num):
digits = []
for x in str(num):
digits.append(int(x))
return digits
print(getDigits(100))
print(getDigits(213))
#Output:
[1,0,0]
[2,1,3]
Another way is we can define a loop to get the remainder of the number after dividing by 10, divide by 10, and then continue the process until we collect all the digits.
def getDigits(num):
digits = []
while num > 0:
digits.append(num % 10)
num = int(num/10)
digits.reverse()
return digits
print(getDigits(100))
print(getDigits(213))
#Output:
[1,0,0]
[2,1,3]
When working with numbers in computer programming, it is useful to be able to easily extract information from our variables.
One such piece of information is the digits that a number is made up of. In Python, we can easily split a number into its digits.
The easiest way to get the digits of an integer in Python is to use list comprehension.
Using list comprehension, we convert the number into a string and get each element of the string.
def getDigits(num):
return [int(x) for x in str(num)]
print(getDigits(100))
print(getDigits(213))
#Output:
[1,0,0]
[2,1,3]
We can also get the digits of a number using a for loop in Python and applying the same logic as in the list comprehension code example.
def getDigits(num):
digits = []
for x in str(num):
digits.append(int(x))
return digits
print(getDigits(100))
print(getDigits(213))
#Output:
[1,0,0]
[2,1,3]
Using Division and Remainders to Split a Number into Digits in Python
We can also split a number into digits using a method without converting the number into a string.
To get the digits of a number using division, we find the remainder of the number divided by 10. Then we will divide by 10, and continue the process until we hit 0.
Doing this method in Python is easy with a while loop.
Below is an example of a function for how to split a number into digits using a loop in Python.
def getDigits(num):
digits = []
while num > 0:
digits.append(num % 10)
num = int(num/10)
digits.reverse()
return digits
print(getDigits(100))
print(getDigits(213))
#Output:
[1,0,0]
[2,1,3]
Hopefully this article has been useful for you to learn how to split a number into digits in Python.