Python 检查字符串是否以列表中的字符串之一结尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18351951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if string ends with one of the strings from a list
提问by TheMeaningfulEngineer
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. Is this true?
我有一个模糊的记忆,for
可以避免循环的显式声明并将其写入if
条件中。这是真的?
采纳答案by falsetru
Though not widely known, str.endswithalso accepts a tuple. You don't need to loop.
虽然并不广为人知,但str.endswith也接受一个元组。你不需要循环。
>>> 'test.mp3'.endswith(('.mp3', '.avi'))
True
回答by Jon Clements
Just use:
只需使用:
if file_name.endswith(tuple(extensions)):
回答by alecxe
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)。
回答by Thomas Wouters
I have this:
我有这个:
def has_extension(filename, extension):
ext = "." + extension
if filename.endswith(ext):
return True
else:
return False
回答by Igor A
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 次循环)
回答by Xxxo
I just came across this, while looking for something else.
我只是在寻找其他东西时遇到了这个。
I would recommend to go with the methods in the os
package. This is because you can make it more general, compensating for any weird case.
我建议使用os
包中的方法。这是因为您可以使它更通用,以补偿任何奇怪的情况。
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.
回答by NeverHopeless
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)
回答by Akash Singh
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']