按顺序检查String中的特定字符

时间:2018-06-11 07:22:05

标签: python

大家好,我有一个关于检查字符串的问题,我想通过订单检查单词中的特定字符

Ah = "a","h","i"
Oo= "o", "y","wh"


text = "whats going on my friend?"
text_splited = text.split()
for word in text_splited:
    print "Checking this :",word
    for ph in Ah:
       if ph in word:
          print ph
    for ph in Oo:
       if ph in word:
          print ph

结果如下:

Checking this : whats
a
h
wh
Checking this : going
i
o
Checking this : on
o
Checking this : my
y
Checking this : friend?
Lip  : i

例如“whats”预期结果是“wh”,“h”,“a”(按顺序) 任何人都可以提供帮助,请:)

由于

1 个答案:

答案 0 :(得分:1)

如果您不关心OoAh元素的混合。这可能有效:

Ah = "a","h","i"
Oo= "o", "y","wh"


text = "whats going on my friend?"
text_splited = text.split()
for word in text_splited:
    list1 = []
    list2 = []
    print("Checking this :",word)
    for ph in Ah:
        list1.append((word.find(ph),ph)) #to preserve the index of element

    list2.extend(list1)
    for ph in Oo:
        list2.append((word.find(ph),ph)) #to preserve the index of element
    list2.sort(key=lambda x:x[0])
    for i in list2:
          if(i[0]>=0):
            print(i[1])

我们只是按排序顺序打印找到的元素。 上述代码的输出是:

Checking this : whats
wh
h
a
Checking this : going
o
i
Checking this : on
o
Checking this : my
y
Checking this : friend?
i