我對編程一般都很陌生,但我是一名快速學習者。我一直在做一個項目。我想製作一個簡單的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