检查字符串是否以列表中的一个字符串结束

时间:2020-11-26 01:37:40

What is the pythonic way of writing the following code?

用python语言编写以下代码的方式是什么?

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条件下编写。这是真的吗?

7 个解决方案

#1


316  

Though not widely known, str.endswith also accepts a tuple. You don't need to loop.

尽管不太为人所知,str.endswith也接受元组。你不需要循环。

>>> 'test.mp3'.endswith(('.mp3', '.avi'))
True

#2


33  

Just use:

只使用:

if file_name.endswith(tuple(extensions)):

#3


4  

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)。

#4


3  

There is two ways: regular expressions and string (str) methods.

有两种方法:正则表达式和string (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(意味着±std. dev. 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(意味着±std. dev. 7,1000000每循环)

#5


0  

I have this:

我有这个:

def has_extension(filename, extension):

    ext = "." + extension
    if filename.endswith(ext):
        return True
    else:
        return False

#6


0  

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.

#7


0  

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.index("."):] in extensions:
    print(True)

#1


316  

Though not widely known, str.endswith also accepts a tuple. You don't need to loop.

尽管不太为人所知,str.endswith也接受元组。你不需要循环。

>>> 'test.mp3'.endswith(('.mp3', '.avi'))
True

#2


33  

Just use:

只使用:

if file_name.endswith(tuple(extensions)):

#3


4  

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)。

#4


3  

There is two ways: regular expressions and string (str) methods.

有两种方法:正则表达式和string (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(意味着±std. dev. 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(意味着±std. dev. 7,1000000每循环)

#5


0  

I have this:

我有这个:

def has_extension(filename, extension):

    ext = "." + extension
    if filename.endswith(ext):
        return True
    else:
        return False

#6


0  

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.

#7


0  

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.index("."):] in extensions:
    print(True)