Files
Python_CookBook_repo/2.字符串和文本/3.shell通配符做字符串匹配.py
2025-09-10 16:12:45 +08:00

26 lines
932 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from fnmatch import fnmatch, fnmatchcase
if __name__ == '__main__':
# 如果想用shell通配符做字符串匹配可以用上面的这两个函数
is_txt = fnmatch("suka.txt", "*.txt")
print(is_txt)
is_txt = fnmatchcase("suka.txt", "??ka.txt")
print(is_txt)
# 注意fnmatchcase不会对输入的name进行大小写标准化而fnmatch会对输入标准化后再进行匹配
# 需要小心的是大小写标准化的模式与底层文件系统相同比如windows不需要区分大小写但是mac要
address = [
'5412 N CLARK ST',
'1060 W ADDISON ST',
'1039 W GRANVILLE AVE',
'2122 N CLARK ST',
'4802 N BROADWAY'
]
# 可以用正则进行筛选
ST = [addr for addr in address if fnmatchcase(addr, "* ST")]
print(ST)
NUM_S = [addr for addr in address if fnmatchcase(addr, '54[0-9][0-9] *CLARK*')]
print(NUM_S)