Python: How to do Case insensitive string replacement
Question: How to do Case insensitive string replacement in Python
Standard tools for string replacement in Python do not offer the case insensitive option for replacement. To perform case insensitive replacement it is necessary to use other tools, available in python.
Using pure regular expression for substitution
This is not very good way of doing this task, because you will need to write pattern for every search pattern, but working very good in simple cases. Therefore I will show you this way only as an example of simple quick code, but do advise you to use next option with pre-compiled regular expression
import re # import module for regulat expressions
test_string = 'One two oNe Two onE tWo ONE TWO one tWO' # string to be replaces
pattern = 'two' # pattern for seach
replace = '222' # patter for replacement
new_string = re.sub(pattern, replace, test_string, flags=re.I)
print( new_string ) # One 222 oNe 222 onE 222 ONE 222 one 222
It is possible to use long flags=re.IGNORECASE and short flags=re.I form of flag.
Using pre-compiled regular expression with re.IGNORECASE option
To do this operation you need to use module re. Also, we will pre-compile search patter into regular expression for future use with ignoring case
import re # import module for regular expressions
test_string = 'One two oNe Two onE tWo ONE TWO one tWO' # string to be replaces
pattern = 'two' # pattern for seach
replace = '222' # patter for replacement
#replace = 'TWO'
compiled = re.compile(re.escape(pattern), re.IGNORECASE) # pre-compiled pattern
new_string = compiled.sub(replace, test_string) # replace with pre-compiled pattern
print( new_string) # One 222 oNe 222 onE 222 ONE 222 one 222
Published: 2021-10-11 08:48:51