无法替换列表中的项“函数对象不支持项分配”

2024-10-05 14:24:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用另一个字符替换列表中的某些字符

import random
import string
import re

def main():
    wordInput()
    computerChoice(wordInput)




def wordInput():
    while(True): #while function to validate user input
        userWord = input("Please choose a word between 5 and 10 letters long: ")
        if len(userWord)<5 or len(userWord)>10:
            print("Error: Word is not between 5 and 10 letters!")
        else:
            break


    #stage 2: printing lines in place of characters to hide the word chosen
    print(" ")
    userWordHidden = list(userWord)
    for i in range(len(userWord)):
        userWordHidden[i] = "-"

    print("Your Word:", end =" ")
    for i in range(len(userWord)):
        print(userWordHidden[i], end =" ")

    print("\n")

    return userWordHidden


def computerChoice(userWordHidden):
    compGuessCount = 0
    compChoice = random.choice(string.ascii_uppercase)

    while(True):
        compGuess = input('Does your word contain the letter %s? \
Please enter "Yes" or "No": ' % (compChoice))
        if compGuess == "Yes" or compGuess == "No":
            break
        else:
            print('Error: Please enter "Yes" or "No"')

    if compGuess == "Yes":
        letterLocation(userWordHidden, compChoice)

def letterLocation(userWordHidden, compChoice):
    userLetterLocation = input('What is the index position of the letter()s \
in the word?: ')
    letterIndex = re.findall("\d", userLetterLocation)

    userWordHidden[1] = "s"

    print(userWordHidden)

这是我正在研究的内容中的一部分,但如果忽略其中大部分内容,只关注函数letterLocation,最后您可以看到我正在尝试用“s”替换userWordHidden index 2,但出现以下错误: TypeError:“function”对象不支持项分配

有人知道为什么吗?我知道你不能更新一个字符串,但你可以用一个列表,但它不工作


Tags: ortheinimportinputlendefyes