I'm trying to replace strings in a nested list.
board = [
['O', 'X', '.'],
['.', 'O', 'X'],
['.', 'O', 'X']
]
this should end up like
board = [
['O', '*', '.'],
['.', 'O', '*'],
['.', 'O', '*']
]
this is what ive tried:
new_board = [[x.replace('X', '*') for x in l] for l in board]
it works like this as a single assingment like this but when i try do it in a function it doesnt work. The function must modify the given board in place; it returns None.
def change_player_char(board, player, new_char):
board = [[new_char if j == player else j for j in i] for i in board]
I call it like:
board = [
['O', 'X', '.'],
['.', 'O', 'X'],
['.', 'O', 'X']
]
change_player_char(board, 'X', '*')
for row in board:
print(row)
[['O', '*', '.'], ['.', 'O', '*'], ['.', 'O', '*']]which appears to be what you want?board = change_player_char(board, 'X', '*')