我对python还是很陌生,我正在尝试制作一个hang子手游戏。我目前有一行代码说word = (random.choice(open("Level1py.txt").readline()))
。
我收到错误'str' object does not support item assignment
。
这是我剩下的代码(对不起,一团糟):
import random
def checkLetter(letter, word, guess_word):
for c in word:
if c == letter:
guess_word[word.index(c)] = c
word[word.index(c)] = '*'
print(guess_word)
word = (random.choice(open("Level1py.txt").readline().split()))
guess_word = ['_' for x in word]
print(guess_word)
while '_' in guess_word:
guess = input('Letter: ')
print(checkLetter(guess, word, guess_word))
答案 0 :(得分:0)
字符串在python中是不可变的。一个简单的解决方法是使用可变的列表:
st = "hello"
ls = list(st)
ls[3] = 'r'
st = ''.join(ls)
print(st)
输出
helro
编辑:这是在您自己的代码中实现它的方式
import random
def checkLetter(letter, word, guess_word):
for c in word:
if c == letter:
guess_word[word.index(c)] = c
word_list = list(word)
word_list[word.index(c)] = "*"
word = ''.join(word_list)
print(guess_word)
word = 'test'
guess_word = ['_' for x in word]
print(guess_word)
while '_' in guess_word:
guess = input('Letter: ')
print(checkLetter(guess, word, guess_word))
请注意,还有其他与此无关的问题,例如打印None
和重复打印
答案 1 :(得分:0)
您也可以使用字典解决问题:
word = "my string" #replace this with your random word
guess_word = {i: '_' for i in set(word)} # initially assign _ to all unique letters
guess_word[' '] = ' ' # exclude white space from the game
wrong_attempts = 0
while '_' in guess_word.values():
guess = input('Letter: ')
if guess in guess_word.keys():
guess_word[guess] = guess
else:
wrong_attempts += 1
if wrong_attempts > 11:
break
printable = [guess_word[i] for i in word]
print(' '.join(printable))
if '_' in guess_word.values():
print('you lost')
else:
print('congratulation, you won')