So I'm trying to split an arbitrarily long user input integer into a list where each entry is 2 digits, and if the number has an odd amount of integers put the only single digit as the first digit. (Where I will then proceed to put a zero in front of it)
I know that putting user integer input into a list looks like:
userintegerlist = [int(i) for i in str(user_input)]
print userintegerlist
And my input (say it's 45346
) will look like [4,5,3,4,6]
. But I want it to look like: [4,53,46]
. Or if input is 68482238
, it will be: [68,48,22,38]
.
Is this possible? All the code is in Python by the way.
The strategy in my code is to create a mirror list and pair up the elements between the two lists
You can group the items using the same iterator on the pair, without using any indexing on the string:
produces
After taking the input string, check if its of odd length, and if yes, prefix a 0 to it. Then , iterate over the string , taking two characters at a time , cast that substring to int , and append it in a list. It's that simple.
You can do it with string methods fairly easily, as other answers have already shown. I direct you to the related grouper recipe in itertools.
I want to mention that it may be more efficient to do it with maths:
Given an input such as
'12345'
what you can do is turn that into a list and then iterate over it in reverse trying to pop two elements at a time and then inserting those at the beginning of the list as integers (after joining them together).If you fail to pop a second element, then you just prefix the popped element with a 0 and also insert that at the beginning of the output list.
Here's a very dirty solution that attempts this:
For an input such as
'345'
you get['03', '45']
And then for
'3456'
you get['34', '56']
Is this what you wanted?