4. Ignore case
re.IGNORECASE is a flag: an option that changes how a pattern matches. It makes letters match regardless of uppercase or lowercase.
re.IGNORECASEis a constant from theremodule;re.Iis its short alias.- Pass it by name as
flags=...tore.search(),re.findall()orre.sub(). It is also the third positional argument ofsearch()andfindall(). flags=0is the default and is case-sensitive.- The match keeps the original spelling: searching
"python"with the flag finds"Python"and.group()returns"Python". - Combine flags with the bitwise OR operator
|, for examplere.IGNORECASE | re.MULTILINE. One flag is enough for these exercises.
Coming from JavaScript? it is the i flag at the end of a JS regex, /python/i. Python passes it as a separate flags argument instead of inside the pattern.
Search ignoring case
Search for "python" in "Python PYTHON python" with flags=re.IGNORECASE. Print the matched text. The first occurrence wins, even when it uses different capitals.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Count every spelling
Use "python" on "Python PYTHON python" with flags=re.IGNORECASE. Store the re.findall() result and print its length.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Keep the original spelling
The flag changes what matches, not the text that is returned. Use "python" on "Python PYTHON python" with flags=re.IGNORECASE and print the whole re.findall() list.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Use the short alias
re.I is the alias of re.IGNORECASE. Search for "dog" in "Dog DOG dog" using flags=re.I and print the first matched text.
Print exactly:
Create a free account to save your progress and unlock chapter 2.