简体   繁体   English

IndexError:字符串索引超出范围python问题

[英]IndexError: string index out of range python problem

I'm working on a game that called 'i will guess the name ur thinking of ' or 'guess my name'.我正在开发一款名为“我会猜你想的名字”或“猜我的名字”的游戏。 The user will enter a letter and the program will try to guess what position of it by using a "for loop" in python:用户将输入一个字母,程序将尝试通过在 python 中使用“for 循环”来猜测它的位置:

list_of_names  = [ ]
userinput_letter = input('QUESTION : write a letter the name has: ')
new_list_of_names = [ ]
for names in list_of_names  :
  if userinput_letter in list_of_names  :
    new_list_of_names.append(names)
randomname = random.choice(new_list_of_names]
position_of_userletter = randomname.find(userinput_letter)
yn = input('QUESTION : does this letter "'+ userinput_letter +'" in the position "'+ str(position_of_userletter ) +'" (yes/no): ' )
if (yn == 'yes') :
    newlist_ofnames = [ ]
    for namesyes in new_list_of_names:
        if ( namesyes in userinput_letter [position_of_userletter] ) :
            newlist_ofnames.append(namesyes)
print(newlist_ofnames)

IndexError: string index out of range IndexError:字符串索引超出范围

As far as I understand userinput_letter is just one letter and you are trying to get some index in it.据我了解userinput_letter只是一个字母,您正试图在其中获取一些索引。 That's why you are getting error.这就是为什么你会出错。

You should do smth like你应该这样做

if (len(namesyes) => position_of_userletter and namesyes[position_of_userletter] == userinput_letter):

First of all on line 5 you should have placed names instead of list_of_names.首先,在第 5 行,您应该放置名称而不是 list_of_names。

Secondly you should place a loop that would re-run random choice if yn is equal to 'no'.其次,您应该放置一个循环,如果 yn 等于“no”,则该循环将重新运行随机选择。

Then instead of this line:然后而不是这一行:

    if ( namesyes in userinput_letter [position_of_userletter] ) :

place this line:放置这一行:

   if (namesyes[postition_of_userletter]== userinput_letter):

Hope it works :)希望它有效:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM