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
4

1 回答 1

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))))
于 2013-10-25T00:08:00.553 回答