2017-03-14 42 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