Add a space infront of an output that is in a loop
Question:
I want to add a spacing infront of the question marks. But its in a loop, adding end=" " will just add more spacing between the question marks. I am curious if there is another method of doing it other than this without importing sys but instead use the print() method:
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')
Output:
?????????
?????????
?????????
?????????
?????????
?????????
?????????
?????????
Answers:
You can replace sys.stdout.write
with print, and to avoid adding a new line when printing, include 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
You can certainly use print()
to do this:
def display_board(board):
pad = " " * 20
for row in board:
line = pad + "".join('?' if column != '@' else '@' for column in row)
print(line)
This works by iterating over each row in the board, then doing a list comprehension over each item in each row, joining the results together into a single string and then padding it with whitespace.
I want to add a spacing infront of the question marks. But its in a loop, adding end=" " will just add more spacing between the question marks. I am curious if there is another method of doing it other than this without importing sys but instead use the print() method:
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')
Output:
?????????
?????????
?????????
?????????
?????????
?????????
?????????
?????????
You can replace sys.stdout.write
with print, and to avoid adding a new line when printing, include 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
You can certainly use print()
to do this:
def display_board(board):
pad = " " * 20
for row in board:
line = pad + "".join('?' if column != '@' else '@' for column in row)
print(line)
This works by iterating over each row in the board, then doing a list comprehension over each item in each row, joining the results together into a single string and then padding it with whitespace.