Using the Question Mark Wildcard
00:00
Let’s take a look at the next wildcard character, the ?
(question mark). The ?
matches any single character in a pattern. It matches any character. In that way it’s similar to the *
, but not any number of characters. Let’s take a look in IDLE.
00:16
Once again, you’re inside of your notes directory, and you can call notes_dir.glob()
. And you matched all of the goals .txt
files before by saying "*.txt"
.
00:29
And there’s another way that you could match them. You could say "goals?.txt"
because this is going match every file that starts with goals
then has one single character and then is followed by .txt
.
00:45
In your case, you have goals1.txt
and goals2.txt
, so both of these should match with this pattern. And you can see because of the pattern, the last character before the .txt
could be anything.
00:59
And that’s what you say with the ?
, but it can’t be more than one character. Yeah, a single one. So this is another way to match. There could be different use cases, of course.
01:10
For example, if you’d use a pattern that says "?oals?.txt"
, in our case, it’s going to match the same two files because we don’t have anything that starts with a different character.
01:26
But if you would have some notes about foals or some notes about coals, then these would match here as well, and with any character at the end. Just like the *
character, you can also use the ?
character more than once in a pattern.
01:41 Now another way of using this is you could, say,
01:46
combine it with the *
character. You could say, give me any file that has any sort of name, but then has a file extension that has exactly two characters.
01:56 Now I’m saying it could be any character, but there’s only two of them. You can pause the video and think about for a moment what this is going to match.
02:06
Consult your directory structure. And then here’s the solution. This is going to match the README.md
file because the first part could be anything, so the stem of the filename could be anything.
02:18
And in this case, it’s README
. And then after the .
you have exactly two characters, which is .md
. And neither goals1
nor goals2.txt
match on this because their file extension has three characters, and you limit it to two by using two ?
wildcards after the dot.
02:40
So these are ways that you can use the ?
wildcard in a pattern. It matches a single character in a pattern. We tried the example of saying "goals?.txt"
, which matches both goals2
and goals1.txt
.
02:54
And you’ve also seen that you can use the wildcard character multiple times in a single pattern, just like the *
character. And you can also combine the two.
Become a Member to join the conversation.