我对编程一般都很陌生,但我是一名快速学习者。我一直在做一个项目。我想制作一个简单的hang子手游戏,但是我遇到了一个障碍,我想在继续之前弄清楚它。如何将项目分配给python中的字符串
我想分配正确的猜测到一个空的变量和打印是他们去,但似乎我不能指定“项目”的字符串。有没有其他方法可以使用?
下面的代码
switch = True
def hangman():
guess_number = 0 # Var that keeps track of the guesses
secret_word = input("What is the secret word?\n>") # Gets the secret word
print("The secret word is %d characters long." % len(secret_word)) # Lenght of secretword
answer = "-" * len(secret_word) # Create empty answer for assigning characters
while switch is True:
guess_number = guess_number + 1 # Counts the guesses
index_num = 0 # Tring to use this to assign correct guesses to answer
user_guess = input("Guess #%d >" % guess_number) # Gets user guess
print("Secret word: " + answer) # prints empty answer as "----"
for each_char in secret_word:
index_num = index_num + 1 # Counting index for assigning to answer variable
print("testing index #" + str(index_num))
if user_guess is each_char:
print("Correct Guess for index #" + str(index_num))
#------> answer[index_num] = each_char <--------
hangman()
如果你真的把字符串拆分成一个列表,其中列表中的每个项目都是单个字母,那将更容易。然后你可以按你想要的方式索引它。如果你想把它打印成一个单词:'print(''。join(my_list中item的项目))' – roganjosh
如果你想存储每个答案的字符,你应该使用一个字典而不是''answer'的字符串。你应该首先查找python数据结构。请发布预期的输出 – nir0s