Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use Shell wildcards to match strings in python

Shulou Source: shulou.com Published: 2022-06-02 08:00:32 10月03日 Update

This article introduces how to use shell wildcards to match strings in python. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

Shell wildcard match string

You want to match strings with Unix Shell wildcards (* .py, * .csv).

The fnmatch module provides two functions, fnmatch () and fnmatchcase (), which can be used to achieve such a match. The usage is as follows:

> 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.txtbrush,' helloC.c']

> [name for name in names if fnmatchcase (name, "* .py")]

['hello.py',' python.py']

These two functions are also useful when dealing with strings that are not filenames. For example, suppose you have a list of street addresses:

> 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 ending

> 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 begins with CLARK

['5412 N CLARK ST']

On how to use the shell wildcard matching string in python to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Tags: Character string wildcard two content function more help good interest address boy buddy beginning data file name article time useful Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Microsoft Huawei Shulou Technology Docker