2017-03-14 39 views
0

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

如果你真的把字符串拆分成一個列表,其中列表中的每個項目都是單個字母,那將更容易。然後你可以按你想要的方式索引它。如果你想把它打印成一個單詞:'print(''。join(my_list中item的項目))' – roganjosh

+0

如果你想存儲每個答案的字符,你應該使用一個字典而不是''answer'的字符串。你應該首先查找python數據結構。請發佈預期的輸出 – nir0s

回答

0

Python中的字符串是不可改變的,它們不能被修改。 你可以把你的字符串作爲一個列表

answer = list("-" * len(secret_word))

然後加入字符一起 answer_str="".join(answer)

0

還有一些其他的方式,已建議。如果你決心繼續字符串的答案,試試這個:

answer = answer[:index_num] + each_char + answer[index_num+1:] 

這通過添加創建一個新字符串(字符串添加是連接)在一起的三個子:第一,通過子的slicing原始字符串從零創建(默認值:[:)高達index_num,不包括在內。即,答案[0] ...答案[index_num-1]。然後each_char,這是一個字符串(或一個字符,相同的差異)。最後,另一個子字符串,從index_num+1運行到最後(默認::])。

+0

這對我有效,謝謝大家的答案!看來列表是更簡單的方法,所以我會回去學習! – Brandon