如何在字符串中分配字符?

时间:2016-07-07 18:17:19

标签: python

这是我的所有代码

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)

当这个被运行时,你会在电路板上发现错误[guess_row] [guess_col] =&#34; X&#34;所以问题是如何在这两个索引处插入字符串X?

1 个答案:

答案 0 :(得分:3)

board是五个5个字符的字符串列表。您正尝试分配给现有字符串中的特定字符,即 mutate 字符串对象。这是不可能的,因为Python中的字符串是immutableTutorial也提到了这一点)。

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

但是,您可以将board组织为字符列表,在这种情况下,您的作业将有效。

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']