在字符串中找到某个字符串

时间:2018-10-14 07:47:15

标签: python

正如标题所说 我被赋予了查找给定字符串中任何形状的Hello单词的任务,这不仅意味着你好,而且我还将不得不找到Hellllloooooo或heeeelllloooo 香港专业教育学院到目前为止写的是这个,但我知道不是100% 如果有任何形状的Hello,我需要我的代码给“是”,如果没有像Heleo或Heeelooo这样的问候,我就需要“ no”

x = input()
answer = []
for i in range(0, len (x)):
y = x.find('h')
answer.extend(x[y])
x = x[y+1:]
i = y
if len(answer) == 5 or len(x) < 5:
    break
y = x.find('e')
answer.extend(x[y])
x = x[y+1:]
i = y
if len(answer) == 5 or len(x) < 5:
    break
y = x.find('l')
answer.extend(x[y])
x = x[y+1:]
i = y
if len(answer) == 5 or len(x) < 5:
    break
y = x.find('l')
answer.extend(x[y])
x = x[y+1:]
i = y
if len(answer) == 5 or len(x) < 5:
    break
y = x.find('o')
answer.extend(x[y])
x = x[y+1:]
i = y
if len(answer) == 5 or len(x) < 5:
    break
if answer == ['h','e','l','l','o']:
    print ('YES')
else:
    print('NO')

3 个答案:

答案 0 :(得分:0)

您可以尝试通过使用正则表达式对输入字符串进行模式匹配来解决问题。您的案例的基本示例:

import re


input_str = input().lower()
pattern = re.compile(r'^h+e+l{2,}o+$')

if pattern.match(input_str):
    print('YES')
else:
    print('NO')

答案 1 :(得分:0)

您可以像这样简单地解决此问题:

user_inp = input().lower()

if 'hello' in user_inp:
    print('yes')
else:
    print('No')

即使字符串在任何位置,“ in”也将检查。

答案 2 :(得分:0)

您可以将collections.Counter()set()结合使用,以创建满足单词为'hello'的条件的条件

from collections import Counter
words = ['hello', 'Hello', 'hhhhhhello', 'hellllllo', 'HHEEELLLllllooO', 'HHHHHHELLOOOOOO']

for word in words:
    x = word.lower()
    if all(Counter(x)[i] > 0 for i in Counter(x)) and Counter(x)['l'] > 1:
        if all(i in 'helo' for i in set(x)):
            print(word)
相关问题