Python Replace String Case-Insensitive Example

Python Replace String Case-Insensitive Example

  • Python
  • 1 min read

To perform case-insensitive string operations in Python, use re module re.sub() method and pass the re.IGNORECASE flag. Below is a simple example to replace a string by ignoring its case:

Python Replace String Case-Insensitive Example

In the following Python program, variable text is having the string 'Python' in upper, lower, and mixed cases. We will replace the string 'Python' with 'snake' using the re.sub() method and will pass the re.IGNORECASE flag to perform case-insensitive replace.

import re
text = 'UPPER PYTHON, lower python, Mixed Python'
print(re.sub('python', 'snake', text, flags=re.IGNORECASE))

Output

UPPER snake, lower snake, Mixed snake

Python re.findall() Example

You can also just find string by ignoring the case using the re.findall() method. Below is an example:

import re
text = 'UPPER PYTHON, lower python, Mixed Python'
print(re.findall('python', text, flags=re.IGNORECASE))

Output

['PYTHON', 'python', 'Python']

Related Tutorials: