Python中消除井字棋棋盘末尾空格的技术求助
井字棋棋盘打印末尾空格问题解决
当前实现的井字棋棋盘打印功能可以正常输出棋盘,但每行末尾的多余空格会导致测试用例不通过,需要调整格式以匹配预期输出。
原代码
def printBoard(plane):#function to print out the current board for w in range(len(plane)): for e in range(len(plane)): if plane[w][e]== 1: print('{:^3}'.format('X'), end="") elif plane[w][e] == -1: print('{:^3}'.format('O'), end="") elif plane[w][e] == 0: print('{:^3d}'.format((len(plane)*w+e)), end="") print()
修改后的代码
def printBoard(plane):#function to print out the current board for w in range(len(plane)): row = [] for e in range(len(plane)): if plane[w][e]== 1: row.append('{:^3}'.format('X')) elif plane[w][e] == -1: row.append('{:^3}'.format('O')) elif plane[w][e] == 0: row.append('{:^3d}'.format((len(plane)*w+e))) # 拼接单元格字符串并移除末尾空格 print(''.join(row).rstrip())
说明
原代码中每个单元格用{:^3}格式化,会生成包含左右空格的3字符内容,逐个打印时会在每行末尾留下多余空格。修改后先将每行的所有单元格字符串收集到列表,拼接成完整行后用rstrip()移除末尾空格,既能保留每个元素的居中格式,又能满足测试用例的无末尾空格要求。
内容的提问来源于stack exchange,提问作者Frankline Misango
相关产品推荐
相关产品推荐

