【发布时间】: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 新手,有时我会遇到函数问题,当然我知道我应该努力学习它。但我正在尝试先学习逻辑,然后很快就会学习工具。