要麼針,我知道我能做到:如果在草垛
if 'hello' in 'hello world':
如果我有幾個像針( '的.css',' .js文件,名爲.jpg', '.gif注意', '.png','.com'),我想檢查這些是否在字符串中。
(注:endswith
不會做,在這種情況下,他們可能沒有後綴)
要麼針,我知道我能做到:如果在草垛
if 'hello' in 'hello world':
如果我有幾個像針( '的.css',' .js文件,名爲.jpg', '.gif注意', '.png','.com'),我想檢查這些是否在字符串中。
(注:endswith
不會做,在這種情況下,他們可能沒有後綴)
您可能會發現any
有用:
haystack = 'hello world'
needles = ['.css', '.js', '.jpg', '.gif', '.png', '.com']
if any(needle in haystack for needle in needles):
pass # ...
for needle in ['.css', '.js', '.jpg', '.gif', '.png', '.com']:
if needle in haystack:
return 'found'
您可以使用正則表達式來「多-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
注意,這個解決方案可以在任意數量的不同文件名的運行並將其與多個不同的擴展!