Dporth
Dporth

Reputation: 21

How to assign a character in a string?

Here is all of my code

from random import randint

board = []

for x in range(5):
    board.append("O" * 5)

def print_board(board):
    for row in board:
        print(" " .join(row))

print_board(board)

def ship_row(board):
    return randint(0, len(board) - 1)

def ship_col(board):
    return randint(0, len(board) - 1)

print("Play some battleship")

ship_row = ship_row(board)
ship_col = ship_col(board)

print(ship_row)
print(ship_col)


for i in range(4):
    print("Turn "), i + 1
        guess_row = int(input("Guess Row:"))
        guess_col = int(input("Guess Col:"))

if guess_row == ship_row and guess_col == ship_col:
    print("Congratulations! You sunk my battleship!")
    break
else:
    if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
        print("Oops, that's not even in the ocean.")
    elif(board[guess_row][guess_col] == "X"):
        print("You guessed that one already.")
    else:
        print("You missed my battleship!")
        board[guess_row][guess_col] = "X"
        if (i == 3):
            print("Game Over")
    print_board(board)

When this is ran you get an error at board[guess_row][guess_col] = "X" so the question is how do I insert the string X at those two indexes?

Upvotes: 0

Views: 425

Answers (1)

Lev Levitsky
Lev Levitsky

Reputation: 65781

board is a list of five 5-character strings. You are trying to assign to a specific character in an existing string, i.e. to mutate a string object. This is not possible, because strings in Python are immutable (the Tutorial also mentions this).

In [1]: row = '0' * 5

In [2]: row
Out[2]: '00000'

In [3]: row[3] = 'X'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-954d03c86f5a> in <module>()
----> 1 row[3] = 'X'

TypeError: 'str' object does not support item assignment

You can, however, organize board as a list of lists of characters, in which case your assignment will work.

In [4]: row = ['0'] * 5

In [5]: row
Out[5]: ['0', '0', '0', '0', '0']

In [6]: row[3] = 'X'

In [7]: row
Out[7]: ['0', '0', '0', 'X', '0']

Upvotes: 3

Related Questions