1. 常用通配符

符号用法
*代替零、一或多个字符
?代替任意一个字符
[abcd]匹配abcd中任意一个字符
[a-z]匹配a-z中任意一个字符

2. fnmatch模块

python的fnmatch模块提供了fnmatch()和fnmatchcase()两个函数,用于字符串匹配,其中fnmatch()匹配的字符不区分大小写,fnmatchcase()区分大小写。

2.1 fnmatch函数

1.*的用法

代码:

from fnmatch import fnmatch

print(fnmatch('test.txt','*'))
print(fnmatch('test.txt','test*'))
print(fnmatch('test.txt','*.txt'))
print(fnmatch('test.txt','test.txt*'))
print(fnmatch('test.txt','*.t'))

运行结果:

True
True
True
True
False

2.?的用法

代码:

from fnmatch import fnmatch

print(fnmatch('test.txt','?est.txt'))
print(fnmatch('test.txt','test.tx?'))
print(fnmatch('test.txt','test.txt?'))
print(fnmatch('test.txt','test.t?'))

运行结果:

True
True
False
False

3.[]的用法

代码:

from fnmatch import fnmatch

print(fnmatch('test.txt','[abcd]est.txt'))
print(fnmatch('test.txt','[rst]est.txt'))
print(fnmatch('test.txt','[a-d]est.txt'))
print(fnmatch('test.txt','[a-z]est.txt'))

运行结果:

False
True 
False
True 

2.2 fnmatchcase函数

fnmatchcase()除了区分大小写以外,用法与fnmatch函数一致。

from fnmatch import fnmatch, fnmatchcase

# fnmatch函数,不区分大小写
print(fnmatch('test.txt','*.txt')) 
print(fnmatch('test.txt','*.TXT')) 

# fnmatchcase函数,区分大小写
print(fnmatchcase('test.txt','*.txt')) 
print(fnmatchcase('test.txt','*.TXT')) 

运行结果:

True
True 
True 
False
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐