在不同的字串中找到一個 'hello' 單詞,其中包含 'hello' 我應該在字串中找到一個 'hello' 單詞,我也是從輸入中給它的。我通過查看某人的答案撰寫了這段代碼給出了以下鏈接的問題。
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))
但我不想用 adef來解決問題。
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它不起作用。我看不到錯誤在哪里。
uj5u.com熱心網友回復:
你的代碼不一樣。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
uj5u.com熱心網友回復:
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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358004.html
