简体   繁体   English

将random.choice变成可变的

[英]Turning random.choice into a mutable

I'm very new to python and I'm trying to make a hangman game. 我是python的新手,我正在尝试制作一个刽子手游戏。 I currently have a line of code saying word = (random.choice(open("Level1py.txt").readline())) . 我目前有一行代码说word = (random.choice(open("Level1py.txt").readline()))

I'm getting the error 'str' object does not support item assignment . 我收到错误'str' object does not support item assignment

Here is the rest of my code (sorry for the mess): 这是我的其余代码(抱歉这个烂摊子):

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))

Strings are immutable in python. 字符串在python中是不可变的。 An easy workaround is to use lists, which are mutable: 一个简单的解决方法是使用可变的列表:

st = "hello"
ls = list(st)
ls[3] = 'r'
st = ''.join(ls)
print(st)

Outputs 输出

helro

Edit: here's how you would implement it in your own code 编辑:这是您在自己的代码中实现它的方式

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))

Note that there are still other issues that have nothing to do with this, like printing None and duplicate printing 请注意,还有其他与此无关的问题,如打印None和重复打印

You can also solve your problem using a dictionary: 您还可以使用字典解决问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM