Search code examples
pythonsplitdivmod

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


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.


Solution

  • 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}).