大家好,我有一个关于检查字符串的问题,我想通过订单检查单词中的特定字符
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”(按顺序) 任何人都可以提供帮助,请:)
由于
答案 0 :(得分:1)
如果您不关心Oo
和Ah
元素的混合。这可能有效:
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