打印功能坚持以前的功能。循环

时间:2013-10-25 00:07:02

标签: python python-3.x

大家好,所以我有这个代码,我添加了(end =“”),这样打印就会出现水平而不是垂直的默认值,但现在这给我带来了一个问题。

这是我的代码,你会看到我的错误。

def main():
    print ("This line should be ontop of the for loop")
    items = [10,12,18,8,8,9 ]
    for i in items:
        print (i, end= " ")

    print("This line should be ontop of the for loop")
    for x in range(1,50, 5):
        print (x, end = " ")

输出:

This line should be ontop of the for lopp
10 12 18 8 8 9 This line should be ontop of the for loop
1 6 11 16 21 26 31 36 41 46

期望的输出:

This line should be ontop of the for loop
10 12 18 8 8 9 
This line should be ontop of the for loop
1 6 11 16 21 26 31 36 41 46

1 个答案:

答案 0 :(得分:2)

循环后添加空打印:

for i in items:
    print (i, end= " ")
print()

这将打印您需要的额外换行符。

或者,使用str.join()map()str()从数字创建一个新的以空格分隔的字符串,使用换行符打印

items = [10, 12, 18, 8, 8, 9]
print(' '.join(map(str, items)))

print(' '.join(map(str, range(1,50, 5))))