How to Split a Number into its Digits in Python?

Estimated read time 2 min read

To split a number into its digits in Python, you can convert the number to a string and then use list comprehension or a loop to extract each digit. Here’s an example:

my_number = 12345

# Convert the number to a string
my_string = str(my_number)

# Split the string into a list of digits
digits = [int(d) for d in my_string]

print(digits)  # Output: [1, 2, 3, 4, 5]

In this example, we define a number my_number and convert it to a string using the str() function. We then use a list comprehension to extract each digit from the string and convert it back to an integer using the int() function. The resulting list of digits is stored in the digits variable.

Alternatively, you can use a loop to extract each digit from the string:

my_number = 12345

# Convert the number to a string
my_string = str(my_number)

# Split the string into a list of digits
digits = []
for d in my_string:
    digits.append(int(d))

print(digits)  # Output: [1, 2, 3, 4, 5]

In this example, we use a for loop to iterate over each character in the string my_string, and append the corresponding integer to the digits list.

Either method should work for splitting a number into its digits in Python.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply