使用'in'进行Python字符串匹配

时间:2016-10-14 16:20:44

标签: string python-3.x dictionary boolean-expression

我遇到了字符串匹配的问题;例如,搜索有时会找到".txt" in "myfile.txt".lower()而不会搜索其他人。如果我运行程序一次,则找不到匹配项,只能在下次运行时找到。

我怀疑问题出在嵌套的for循环中。任何人都可以发现错误(甚至可能建议采用更清洁,更有效的方法来实现这一目标)?

def find_string_in_filename_and_move(dir_filelist_dict, string_dict):
    """
    Iterates through files in directories, for each file searches for strings
    Moves file to new folder if string matches
    :param dir_filelist_dict: dict of dirs with associated file list
    :param string_dict: dict or strings with associated home dir
    :return: None
    """
    for dir_name, files in dir_filelist_dict.items():
        for search_string, folder in string_dict.items():
            for f in files:
                if search_string in f.lower():  # problem encountered here
                    old_path = path.join(dir_name, f)
                    new_path = path.join(dir_name, folder)
                    if not path.isdir(new_path):
                        mkdir(new_path)
                    move(old_path, new_path)
                    dir_filelist_dict[dir_name].remove(f)
    return None

0 个答案:

没有答案