【问题标题】: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?

【问题讨论】:

标签: python-3.x


【解决方案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,我很感激。
  • 如果我能帮到你,我会很高兴投赞成票 :)
猜你喜欢
  • 2017-10-13
  • 2011-06-20
  • 1970-01-01
  • 2020-12-10
  • 2023-02-06
  • 2018-03-02
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
相关资源
最近更新 更多