Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在字符串中查找特定字符串_Python - Fatal编程技术网

Python 在字符串中查找特定字符串

Python 在字符串中查找特定字符串,python,Python,正如标题所说 我的任务是在给定的字符串中找到任意形状的单词Hello,这意味着它不仅是Hello,而且我还必须找到hellllloooo或heeellloooo 到目前为止我写的是这个,但我知道它不是100%有效的 我需要我的代码给'是'如果有一个你好在任何形状和'否'如果没有Hello像Heleo或Heeelooo x = input() answer = [] for i in range(0, len (x)): y = x.find('h') answer.extend(x[y]) x

正如标题所说 我的任务是在给定的字符串中找到任意形状的单词Hello,这意味着它不仅是Hello,而且我还必须找到hellllloooo或heeellloooo 到目前为止我写的是这个,但我知道它不是100%有效的 我需要我的代码给'是'如果有一个你好在任何形状和'否'如果没有Hello像Heleo或Heeelooo

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')

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

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')

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

user_inp = input().lower()

if 'hello' in user_inp:
    print('yes')
else:
    print('No')
即使字符串出现在任何位置,“in”也会进行检查。

您可以使用集合。计数器与set组合使用,以创建符合单词“hello”标准的条件

“hheeellloooo”中的“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)