2014-10-28 63 views
2

要么针,我知道我能做到:如果在草垛

if 'hello' in 'hello world': 

如果我有几个像针( '的.css',' .js文件,名为.jpg', '.gif注意', '.png','.com'),我想检查这些是否在字符串中。

(注:endswith不会做,在这种情况下,他们可能没有后缀)

回答

5

您可能会发现any有用:

haystack = 'hello world' 
needles = ['.css', '.js', '.jpg', '.gif', '.png', '.com'] 
if any(needle in haystack for needle in needles): 
    pass # ... 
2
for needle in ['.css', '.js', '.jpg', '.gif', '.png', '.com']: 
    if needle in haystack: 
    return 'found' 
1

您可以使用正则表达式来“多-match“:

import re 
pat = r'(\.css|\.js|\.jpg|\.gif|\.png|\.com)' 
files = ['file.css', 'file.exe', 'file.js', 'file.bat'] 
for f in files: 
    if re.findall(pat, f): 
     print f 

输出

file.css 
file.js 

注意,这个解决方案可以在任意数量的不同文件名的运行并将其与多个不同的扩展!