Find All Pattern Matches
And you can do that already in the search by using something that’s called a match group. So if you wrap something in brackets (
()), then you create a match group. So this is the first match group here.
And while the whole pattern looks only for the word
"secret", followed by either a dot or a comma, what you get returned from
.findall() here is only going to be the word
"secret", what you’re wrapping inside of this match group.
01:38 So that’s pretty neat, and it gives you a lot of power to look around. Like just for the fun of it, let me show you that you could also do something differently depending on how you create these match groups. So I could also say, give me back just the last character and then the punctuation character.
02:07 And you could see that in this case, you always got back a list of strings. What the actual return value is, it could also be a list of tuples, and that’s when you’re using more than one capturing group in here.
02:31 If I run this, you can see that the return value is still a list, but instead of then containing a string, you get a tuple that contains the strings of all of the capturing groups per find, basically.
So that’s just something to keep in mind. If you only have one capturing group, then
.findall() returns a list of strings. If you have more than one capturing group in your pattern, then it’s going to return a list of tuples. Okay, pretty cool.
You don’t have the additional information such as the start and the end index. So in the next lesson you’ll see how you can use, again, a different function to actually get back multiple
Match objects that you can work with more.
Become a Member to join the conversation.