2011-12-10 35 views
1

我试图搜索字符串中的单词。如何搜索字符串中的单词

match = 'File' 
s2 = 'name of File: is .jpg' 
if match not in s2: 
    print 'ok' 

和它的工作。我可以用list来做到这一点吗?

match = ['File','Category'] 
+0

你要搜索的原话?即,如果您的搜索词是'foo',您是否希望它匹配'foobar'中的'foo'? –

+0

@Tim Pietzcker不是确切的单词。 – Kulbir

回答

4

当然可以。因此,我们检查match中的每个单词,如果该单词在s2中有或没有。

for word in match: 
    if word not in s2: 
     print 'ok' 

或简单的一行 -

[word for word in match if word not in s2] 
0
for entry in match: 
    if entry not in s2: 
    print 'ok' 
0
>>> s2.split() 
['name', 'of', 'File:', 'is', '.jpg'] 
>>> s = s2.split() 
>>> s[2] 
'File:' 
>>> match in s[2] 
True 
1

如果你只是寻找一个字的存在:

>>> 'St' in 'Stack' 
True 

如果你正在寻找它的位置也是:

>>> ("stack").find("st") 
0 

注意:下面的内容已被提取从http://docs.python.org/library/stdtypes.html,而上面的内容进行了测试独创矿的盛情参考:

语法:

str.find(sub[, start[, end]]) 

应当返还最低找到子字符串sub的字符串中的索引,使得sub被包含在切片s [start:end]中。可选参数开始和结束被解释为切片符号。如果未找到子项,则返回-1。

参考:

http://docs.python.org/library/stdtypes.html < - 看了就知道了更加丰富多彩的更多方法聚焦搜索

相关问题