Taking an input of any length of number and splitting them one character each

336 Views Asked by At

I'm a few weeks into learning python and I am trying to write a script that takes an input of any length of numbers and splits them in one-character lengths. like this: input:

123456

output:

1           2            3            4            5            6

I need to do this without using strings, and preferably using divmod... something like this:

 s = int(input("enter numbers you want to split:"))
     while s > 0:
         s, remainder = divmod(s, 10)

I'm not sure how to get the spacing right.

Thank you for the help.

4

There are 4 best solutions below

2
On BEST ANSWER

What about the following using the remainder:

s = 123456
output = []
while s > 0:
    s, r = divmod(s, 10)
    output.append(r)

fmt='{:<12d}'*len(output)
print fmt.format(*output[::-1])

Output:

1           2           3           4           5           6

This also uses some other useful Python stuff: the list of digits can be reversed (output[::-1]) and formatted into 12-character fields, with the digit aligned on the left ({:<12d}).

0
On

You can iterate over Python string amd use String.join() to get result:

>>>'  '.join(str(input("Enter numbers you want to split: ")))
Enter numbers you want to split: 12345
1  2  3  4  5  
5
On

As your priority is to use divmod, you can do it like this:

lst=[]
while s>0:
    s, remainder = divmod(s, 10)
    lst.append(remainder)

for i in reversed(lst):
    print i,

Output:

enter numbers you want to split:123456
1 2 3 4 5 6

You can use join() to achieve that. Cast to string if your are using python 2.*

s = input("enter numbers you want to split:")
s= str(s)
digitlist=list(s)
print " ".join(digitlist)

In case, you are in need of integers, just do it.

intDigitlist=map(int,digitlist)
2
On

Try it with mod:

while x > 0:
   x = input
   y = x % 10
   //add y to list of numbers
   x = (int) x / 10

e.g. if x is 123:

123 % 10 is 3 -> you save 3. the Integer value of 123 / 10 is 12. Then 12 % 10 is 2 -> you save 2 Int of 12 / 10 is 1. 1 % 10 = 1 -> you save 1

Now you have all numbers. You can invert the list after that to have it like you want.