Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Shell wildcards to match strings in python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report