【Python】python通配符,使用通配符进行字符串匹配 |
您所在的位置:网站首页 › python字符串查找特定字符串 › 【Python】python通配符,使用通配符进行字符串匹配 |
文章目录
1. 常用通配符2. fnmatch模块2.1 fnmatch函数2.2 fnmatchcase函数
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 False2.?的用法 代码: 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 False3.[]的用法 代码: 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 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |