Using the Question Mark Wildcard
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.
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
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
In your case, you have
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.
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.
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.
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,
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.
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.
And in this case, it’s
README. And then after the
. you have exactly two characters, which is
.md. And neither
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.
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
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.