如何检测变量中的字符串

Posted

技术标签:

【中文标题】如何检测变量中的字符串【英文标题】:how to detect a string in a variable 【发布时间】:2021-07-05 16:18:19 【问题描述】:
x = input("enter input: ")

if x == "hello":
    print ("it does")

即使 x 有其他字符/字符串,我如何检测 x 是否存储了 hello?

【问题讨论】:

这能回答你的问题吗? How do I check if a given Python string is a substring of another one? 请拨打tour、阅读what's on-topic here、How to Ask和question checklist。请注意asking on Stack Overflow is not a substitute for doing your own research. 【参考方案1】:

如果输入的输入是单个字符串,则下面的 x 将是一个元素的数组,如果输入的输入是空格分隔的字符串(字符串的字符串),那么 x 将是多个字符串的数组,下面的代码处理这两个选项

x = input("Enter input: ").split()
for y in x:
   if y=="hello"
      print("it does")

【讨论】:

我知道这行得通,但您介意解释一下它是如何工作的吗?【参考方案2】:

这就像使用 in 关键字一样简单。

x = "123hellomore"
if "hello" in x:
    print("Hi there")

这仅检测hello,如果它通畅所以仍然在一个单词中(不像“**hel*lo”)

【讨论】:

谢谢lighstack,我很感激。 如果我能帮到你,我会很高兴投赞成票 :)

以上是关于如何检测变量中的字符串的主要内容,如果未能解决你的问题,请参考以下文章