【问题标题】:Add a space infront of an output that is in a loop在循环中的输出前添加一个空格
【发布时间】:2023-01-26 15:51:42
【问题描述】:

我想在问号前添加一个间距。但它在一个循环中,添加 end=" " 只会在问号之间增加更多的间距。我很好奇是否还有另一种方法可以在不导入 sys 的情况下执行此操作,而是使用 print() 方法:

import sys

def display_board(board):
    for rows in board:
        sys.stdout.write(" "* 20)
        for columns in rows:
            # Display "?" for hidden cells and the actual letter for visible cells
            sys.stdout.write(("?" if columns != "@" else "@"))
        sys.stdout.write('\n')

输出:

                    ?????????
                    ?????????
                    ?????????
                    ?????????
                    ?????????
                    ?????????
                    ?????????
                    ?????????

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以用 print 替换 sys.stdout.write,并且为了避免在打印时添加新行,请包含 end=''

    def display_board(board):
        for rows in board:
            print(" " * 20, end="")
            for columns in rows:
                # Display "?" for hidden cells and the actual letter for visible cells
                print("?" if columns != "@" else "@", end="")
            print() // Prints newline
    

    【讨论】:

      猜你喜欢
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      相关资源
      最近更新 更多