如何检查字符串是否在python中包含字母的序列号?

时间:2018-11-30 12:04:52

标签: python-3.x

我有一个输入,就是一个词。 如果我的输入内容包含python,请打印True。如果不是,请打印False。 例如: 如果输入是puytrmhqoln打印True(因为它包含python的字母,但是python之间有一些字母) 如果输入为pythno,则打印False(因为n后面是o型)

3 个答案:

答案 0 :(得分:0)

我找到了答案。

import sys
inputs = sys.stdin.readline().strip()
word = "python"
for i in range(len(inputs)):
    if word == "": break
    if inputs[i] == word[0]:
        word = word[1:]
if word == "":
    print("YES")
else:
    print("NO")

它适用于带有双字母的hello之类的单词,也适用于python

答案 1 :(得分:-1)

遍历字符串的每个字符。并查看当前字符是否与您要查找的字符串中的下一个字符相同:

strg = "pythrno"
lookfor = "python"
longest_substr = ""
index = 0
max_index = len(lookfor)
for c in strg:
    if c == lookfor[index] and index < max_index:
        longest_substr += c
        index += 1
print(longest_substr)

会给你

pytho

您现在可以简单地比较longest_substrlookfor并将其包装在专用函数中。

答案 2 :(得分:-1)

我希望这段代码会有用:

变体1(查找整个单词):

s_word = 'python'
def check(word):
    filtered_word = "".join(filter(lambda x: x in tuple(s_word), tuple(word)))
    return filtered_word == s_word

print(check('puytrmhqoln'))
# returns True
print(check('pythno'))
# returns False

变体2(逐个字符查找,验证字符顺序):

s_word = 'python'
def check(word):
    for i in s_word:
        pre_sym = s_word[s_word.index(i) - 1] if s_word.index(i) > 0 else i
        if word.index(i) < word.index(pre_sym):
            return False
    return True


print(check('pyttthorne'))
# returns True
print(check('puytrmhqoln'))
# returns True
print(check('pythno'))
# returns False

变体3(逐个字符查找):

def check(word):
    w_slice = word
    for c in s_word:
        if w_slice.find(c) < 0:
            return False
        w_slice = word[word.index(c) + 1:]
    return True


s_word = 'hello'
print(check('helo'))
# returns False
print(check('helolo'))
# returns True

s_word = 'python'
print(check('pyttthorne'))
# returns True
print(check('puytrmhqoln'))
# returns True
print(check('pythno'))
# returns False

变体4(带有正则表达式):

import re
s_word = _REFERENCE_WORD_
# convert the reference word to a regular expression
re_expr = re.compile(r'.*%s{1}.*' % '{1}.*'.join(s_word))

用法:

print(True if re_expr.match(_ENTERED_WORD_) else False)    

“ hello”示例:

s_word = 'hello'
re_expr = re.compile(r'.*%s{1}.*' % '{1}.*'.join(s_word))
for w in ('helo', 'helolo', 'hlelo', 'ahhellllloou'):
    print(f'{s_word} in {w} -> {True if re_expr.match(w) else False}')
# returns:
# hello in helo -> False
# hello in helolo -> True
# hello in hlelo -> False
# hello in ahhellllloou -> True

“ python”示例:

s_word = 'python'
re_expr = re.compile(r'.*%s{1}.*' % '{1}.*'.join(s_word))
for w in ('pyttthorne', 'puytrmhqoln', 'pythno'):
    print(f'{s_word} in {w} -> {True if re_expr.match(w) else False}')
# returns:
# python in pyttthorne -> True
# python in puytrmhqoln -> True
# python in pythno -> False