Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find strings in list using wildcard

I am looking for some file names in a list using a wildcard.

from datetime import date
dt = str("RT" + date.today().strftime('%d%m'))
print dt # RT0701

Basically I need to find this pattern dt + "*.txt" :

RT0701*.txt

In this list:

l = ['RT07010534.txt', 'RT07010533.txt', 'RT02010534.txt']

How can i do that with a for loop?

like image 399
user2990084 Avatar asked Jan 07 '16 16:01

user2990084


People also ask

How do you use wildcards in strings?

Wildcards (*,?,~) can be used in conditions to represent one or more characters. The & character is used to concatenate, or join, two or more strings or the contents of referenced cells. Some examples of the use of the concatenation operator are: "Abc"&"Def" returns "AbcDef".

How do you do a wildcard search in Python?

The asterisk ( ∗) An asterisk ∗ is used to specify any number of characters. It is typically used at the end of a root word. This is great when you want to search for variable endings of a root word. For example, searching for work* would tell the database to look for all possible word-endings to the root “work”.

How do you do a wildcard search?

Wildcard SearchesTo perform a single character wildcard search use the "?" symbol. To perform a multiple character wildcard search use the "*" symbol. You can also use the wildcard searches in the middle of a term.

Can you use wild cards in the Find dialog box?

To use wildcards, you will need to use the Find and Replace dialog box and expand it to display more options. You can then select the option to Use wildcards. A wildcard can replace one or more characters in a string of text or numbers.


1 Answers

You can use fnmatch.filter() for this:

import fnmatch
l = ['RT07010534.txt', 'RT07010533.txt', 'RT02010534.txt']
pattern = 'RT0701*.txt'
matching = fnmatch.filter(l, pattern)
print(matching)

Outputs:

['RT07010534.txt', 'RT07010533.txt']
like image 156
Andy Avatar answered Sep 23 '22 15:09

Andy