[英]Check if string ends with one of the strings from a list
What is the pythonic way of writing the following code?编写以下代码的pythonic方式是什么?
extensions = ['.mp3','.avi']
file_name = 'test.mp3'
for extension in extensions:
if file_name.endswith(extension):
#do stuff
I have a vague memory that the explicit declaration of the for
loop can be avoided and be written in the if
condition.我有一个模糊的记忆,可以避免
for
循环的显式声明并将其写入if
条件中。 Is this true?这是真的?
Though not widely known, str.endswith also accepts a tuple. 虽然并不广为人知,但str.endswith也接受一个元组。 You don't need to loop.
你不需要循环。
>>> 'test.mp3'.endswith(('.mp3', '.avi'))
True
只需使用:
if file_name.endswith(tuple(extensions)):
Take an extension from the file and see if it is in the set of extensions: 从文件中获取扩展名,看看它是否在扩展集中:
>>> import os
>>> extensions = set(['.mp3','.avi'])
>>> file_name = 'test.mp3'
>>> extension = os.path.splitext(file_name)[1]
>>> extension in extensions
True
Using a set because time complexity for lookups in sets is O(1) ( docs ). 使用集合因为集合中查找的时间复杂度为O(1)( docs )。
There is two ways: regular expressions and string (str) methods. 有两种方法:正则表达式和字符串(str)方法。
String methods are usually faster ( ~2x ). 字符串方法通常更快(~2x)。
import re, timeit
p = re.compile('.*(.mp3|.avi)$', re.IGNORECASE)
file_name = 'test.mp3'
print(bool(t.match(file_name))
%timeit bool(t.match(file_name)
792 ns ± 1.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) 每回路792 ns±1.83 ns(平均值±标准偏差,7次运行,每次1000000次循环)
file_name = 'test.mp3'
extensions = ('.mp3','.avi')
print(file_name.lower().endswith(extensions))
%timeit file_name.lower().endswith(extensions)
274 ns ± 4.22 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) 每个环路274 ns±4.22 ns(平均值±标准偏差,7次运行,每次1000000次循环)
I just came across this, while looking for something else. 我只是想到了这个,同时寻找其他东西。
I would recommend to go with the methods in the os
package. 我建议使用
os
包中的方法。 This is because you can make it more general, compensating for any weird case. 这是因为你可以使它更通用,补偿任何奇怪的情况。
You can do something like: 你可以这样做:
import os
the_file = 'aaaa/bbbb/ccc.ddd'
extensions_list = ['ddd', 'eee', 'fff']
if os.path.splitext(the_file)[-1] in extensions_list:
# Do your thing.
I have this: 我有这个:
def has_extension(filename, extension):
ext = "." + extension
if filename.endswith(ext):
return True
else:
return False
Another possibility could be to make use of IN statement: 另一种可能性是使用IN语句:
extensions = ['.mp3','.avi']
file_name = 'test.mp3'
if "." in file_name and file_name[file_name.rindex("."):] in extensions:
print(True)
another way which can return the list of matching strings is 另一种可以返回匹配字符串列表的方法是
sample = "alexis has the control"
matched_strings = filter(sample.endswith, ["trol", "ol", "troll"])
print matched_strings
['trol', 'ol']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.