简体   繁体   English

检查字符串是否以列表中的字符串之一结尾

[英]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.

相关问题 使用 endswith() 检查一个列表中的字符串是否以另一个列表中的字符串结尾? - Use endswith() to check if a string in one list ends with a string from another list? 检查字符串是否包含列表中的至少一个字符串 - Check if a string contains at least one of the strings in a list 检查字符串列表,然后与特定字符串匹配以将其从字符串列表中删除 - Check list of strings and then match with the specific string to delete it from the list of strings Python 检查字符串列表中的句子中是否存在字符串 - Python Check if a string is there in a sentence from a list of strings 检查字符串是否不包含列表中的字符串 - Check if string not contains strings from the list Python:检查以哪个元组项目字符串结尾(如果它以一个结尾) - Python: Check which tuple item string ends with, if it ends with one at all 检查列表中的任何条目是否以指定的字符串结尾 - Check if any entries in a list ends with a specified string 检查列表或字符串以查看是否存在另一个列表中的字符串 - Check list or strings to see if a string from another list is present 如何检查字符串列表中的任何字符串是否是字符串的 substring? - How to check if any string from a list of strings is a substring of a string? 检查字符串列表中是否存在来自文件的字符串:python - check if a string from a file exists in a list of list of strings: python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM