I just started programming with python a couple days ago with no prior experience in programming.
几天前,我刚开始使用python编程,以前没有编程经验。
I've been following tutorials online and decided to challenge myself by making a hangman-esque game. I'm trying to make it so that a guess replaces the position an alphabet in the hidden word but python is returning this error. Right now the word is called name and the hidden_name are just #'s in the same length.
我一直在关注在线教程,并决定通过制作一个类似刽子手的游戏来挑战自己。我试着让猜测取代了隐藏单词中的字母表但是python返回了这个错误。现在,这个词叫做name,而hidden_name的长度是一样的。
name = input ("what is your name ::")
hidden_name = ("#" * len(name))
print (hidden_name)
guess = input ("Guess a letter ::")
def guess_update(guess, name, hidden_name):
right = guess in name
i = 0
for c in name:
if c == guess:
hidden_name[i] = c
i += 1
if guess in name:
guess_update(guess, name, hidden_name)
print ("Your progess is ::", hidden_name)
Thanks for helping this newbie out :)
谢谢你帮助这个新手。
2 个解决方案
#1
2
Strings in Python are immutable, so you cannot do this:
Python中的字符串是不可变的,所以不能这样做:
hidden_name[i] = c
One option which will achieve the desired effect for your game is:
一种可以达到你的游戏预期效果的选择是:
hidden_name = hidden_name[:i] + c + hidden_name[i+1:]
This works because you are creating a new string using concatenation, and re-assigning the result back to the variable, rather than attempting to edit the existing string.
这是因为您正在使用连接创建一个新的字符串,并将结果重新分配给变量,而不是尝试编辑现有的字符串。
#2
1
Strings in python are inmutable, so you cannot change its content. One solution would be to split the string, change the letter and stick it back together:
python中的字符串是不可修改的,所以不能更改其内容。一种解决办法是把绳子分开,改变字母,再把它粘在一起:
splitted = list(hidden_name)
splitted[i] = c
hidden_name = ''.join(splitted)
#1
2
Strings in Python are immutable, so you cannot do this:
Python中的字符串是不可变的,所以不能这样做:
hidden_name[i] = c
One option which will achieve the desired effect for your game is:
一种可以达到你的游戏预期效果的选择是:
hidden_name = hidden_name[:i] + c + hidden_name[i+1:]
This works because you are creating a new string using concatenation, and re-assigning the result back to the variable, rather than attempting to edit the existing string.
这是因为您正在使用连接创建一个新的字符串,并将结果重新分配给变量,而不是尝试编辑现有的字符串。
#2
1
Strings in python are inmutable, so you cannot change its content. One solution would be to split the string, change the letter and stick it back together:
python中的字符串是不可修改的,所以不能更改其内容。一种解决办法是把绳子分开,改变字母,再把它粘在一起:
splitted = list(hidden_name)
splitted[i] = c
hidden_name = ''.join(splitted)