输入任意长度的数字并将它们分成一个字符

时间:2015-10-06 13:27:41

标签: python split divmod

我在学习python几个星期后,我正在尝试编写一个脚本,该脚本接受任意长度的数字输入并将它们分成一个字符长度。像这样: 输入:

  

123456

输出:

1           2            3            4            5            6

我需要在不使用字符串的情况下执行此操作,最好使用divmod ... 像这样的东西:

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

我不确定如何使间距正确。

感谢您的帮助。

4 个答案:

答案 0 :(得分:2)

优先使用divmod,您可以这样做:

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

for i in reversed(lst):
    print i,

输出:

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

您可以使用join()来实现这一目标。如果您正在使用python 2。*

,则转换为字符串
s = input("enter numbers you want to split:")
s= str(s)
digitlist=list(s)
print " ".join(digitlist)

如果你需要整数,那就去做吧。

intDigitlist=map(int,digitlist)

答案 1 :(得分:0)

尝试使用mod:

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

e.g。如果x是123:

123%10是3 - >你节省3。 整数值123/10是12。 然后12%10是2 - >你节省2 12/10的Int为1。 1%10 = 1 - >你保存1

现在你有了所有号码。您可以在此之后反转列表以使其符合您的要求。

答案 2 :(得分:0)

使用余下的内容如下:

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

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

输出:

1           2           3           4           5           6

这也使用了一些其他有用的Python东西:数字列表可以颠倒(output[::-1])并格式化为12个字符的字段,数字在左边对齐({:<12d})。 / p>

答案 3 :(得分:0)

你可以迭代Python字符串amd使用String.join()来获得结果:

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