2013-10-25 32 views
0

大家好,所以我有这个代码,我添加了(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 

回答

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))))