简体   繁体   English

如何检查用户输入是否在列表中的随机字符串中?

[英]How can I check if user input is in a random string from a list?

I am trying to program hangman.我正在尝试对刽子手进行编程。 I am quite new and am wondering something.我很新,想知道一些事情。 I already figured this out我已经想通了

 x = "Hello World"
print(x[2])
print(x[6])
print(x[10])

The output is output 是

l
W
d

I am wondering if i can write this:我想知道我是否可以这样写:

import random
list = ["Hi","Hello","Hi wrld","Hello world"]
chosen = list(random.randint(1,4)
nr_of_letters = len(chosen)
# j is the letter the user guesses
j = input()
if j == chosen[0,nr_of_letters]:
   print("something")
else:
   print("something else")

The error info I get is that the number has to be an integer. If I try writing it differently I have 2 options.我得到的错误信息是该号码必须是 integer。如果我尝试以不同的方式编写它,我有 2 个选项。

#the first option is :
j = int(input ())
#the second option is:
if j == chosen[0,int(nr_of_letters)]:

neither of them work.他们都不工作。 Please how can I write that correctly.请问我怎样才能正确地写那个。

So first, to choose a random word from a list:所以首先,从列表中选择一个随机单词:

import random
words = ["Hi","Hello","Hi wrld","Hello world"]
chosen = random.choice(words)
# Chosen will now be one of the words in the list

Since you're trying to code hangman I assume you know you'll need a while loop to allow the user to keep giving input so I'll just work with what you've given here as an example.由于您正在尝试编写 hangman 代码,我假设您知道您需要一个 while 循环来允许用户继续提供输入,所以我将只使用您在此处给出的内容作为示例。 So for checking if they entered a correct letter:因此,为了检查他们是否输入了正确的字母:

j = input()
if j in chosen:
    print("something")
else:
    print("something else")

Is that ok?那样行吗?

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

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