【问题标题】:Finding a 'hello' word in a different string, which it has 'hello' in it(additional)在不同的字符串中查找“hello”单词,其中包含“hello”(附加)
【发布时间】:2021-12-26 23:28:52
【问题描述】:

Finding a 'hello' word in a different string, which it has 'hello' in it 我应该在一个字符串中找到一个“你好”这个词,我也是从输入中给出的。我通过查看某人对以下链接问题的答案编写了这段代码。

firststring = input() #ahhellllloou
to_find = "hello"

def check_string(firststring, to_find):
   c = 0
   for i in firststring:
       #print(i)
       if i == to_find[c]:
           c += 1
       if c == len(to_find):
           return "YES"
   return "NO"

print(check_string(firststring, to_find))

但我不想使用def 来解决问题。

hello = "hello"
counter_hello = 0
bool_hello = False

for letter in string:
    if letter == hello[counter_hello]:
        counter_hello += 1
    if counter_hello == len(hello):
        bool_hello = True

if bool_hello == True:
    print("YES")
else:
    print("NO")

对于hello 字符串,它工作正常。也适用于pnnepelqomhhheollvlo。 但是当我给它ahhellllloou 它不起作用。 我看不到错误在哪里。

【问题讨论】:

  • 请解释你为什么不想使用函数
  • 如果您读到一个不在单词 hello 中的字母,您忘记将计数器重置为 0。这就是它匹配 helXXXXXXlo 的原因。
  • 我是 python 新手,有时我会遇到函数问题,当然我知道我应该努力学习它。但我正在尝试先学习逻辑,然后很快就会学习工具。

标签: python string function


【解决方案1】:

您的代码不一样。 return 语句需要通过打破循环来解释

string = "ahhellllloou"
to_find = "hello"

match = False
c = 0
for i in string:
   if i == to_find[c]:
       c += 1
   if c == len(to_find):
       match = True
       break
print("YES" if match else "NO")

请注意,不需要循环

>>> import re
>>> m = re.search('.*'.join('hello'), 'ahhellllloou')
>>> m is not None
True
>>> m = re.search('.*'.join('hello'), 'ahhellllliu')
>>> m is None
True

【讨论】:

  • 谢谢。我应该学会使用 re 库。
  • 如果这解决了您的问题,请随时使用帖子旁边的复选标记接受答案
【解决方案2】:
counter_hello = 0
bool_hello = False

for letter in 'ahhellllloou':
    #print('letter: ', letter);
    #print(hello[counter_hello])
    if letter == hello[counter_hello] and counter_hello != len(hello) - 1:
        counter_hello += 1
    if counter_hello == len(hello) - 1:
        bool_hello = True

if bool_hello == True:
    print("YES")
else:
    print("NO")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 2020-05-02
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多