python中怎么利用shell通配符匹配字符串

这篇文章给大家介绍python中怎么利用shell通配符匹配字符串,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。


shell通配符匹配字符串

想用Unix Shell通配符(*.py,*.csv)匹配字符串。

fnmatch 模块提供了两个函数——fnmatch() 和 fnmatchcase() ,可以用来实现这样的匹配。用法如下:

>>> from fnmatch import fnmatch,fnmatchcase
>>> fnmatchcase("python.py","*.py")
True
>>> names = ["hello.py","python.py","1.txt",'helloC.c']
>>> names
['hello.py', 'python.py', '1.txt', 'helloC.c']
>>> [name for name in names if fnmatchcase(name,"*.py")]
['hello.py', 'python.py']
   

这两个函数在处理非文件名的字符串时候也是很有用的。比如,假设你有一个街道地址的列表数据:

>>> addresses = [
'5412 N CLARK ST',
'1060 W ADDISON ST',
'1039 W GRANVILLE AVE',
'2122 N CLARK ST',
'4802 N BROADWAY',
]
>>> result = [place for place in addresses if fnmatchcase(place,"*ST")] #ST结尾
>>> result
['5412 N CLARK ST', '1060 W ADDISON ST', '2122 N CLARK ST']
>>> result = [place for place in addresses if fnmatchcase(place,"54[1-9][1-9]*CLARK*ST")]
>>> result #54开头包含CLARK
['5412 N CLARK ST']

关于python中怎么利用shell通配符匹配字符串就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。