I'm new to Python. What I want to do is take a three-digit integer like 634
, and split it so it becomes a three-item list, i.e.
digits = [ 6, 3, 4 ]
Any help in this would be much appreciated.
To split an integer into digits:Use the str() class to convert the integer to a string. Use a for loop to iterate over the string. Use the int() class to convert each substring to an integer and append them to a list.
You can convert the number to a string, then iterate over the string and convert each character back to an integer:
>>> [int(char) for char in str(634)]
[6, 3, 4]
Or, as @eph rightfully points out below, use map():
>>> map(int, str(634)) # Python 2
[6, 3, 4]
>>> list(map(int, str(634))) # Python 3
[6, 3, 4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With