【问题标题】:print function sticks to previous function. Loops打印功能坚持以前的功能。循环
【发布时间】:2013-11-03 22:14:04
【问题描述】:

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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    在循环后添加一个空打印:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 1970-01-01
      • 1970-01-01
      • 2014-11-29
      • 2022-01-01
      • 2013-09-02
      • 1970-01-01
      相关资源
      最近更新 更多