The string type doesn't support this. You're probably best off using the regular expression sub method with the re.IGNORECASE option.
>>> import re
>>> insensitive_hippo = re.compile(re.escape('hippo'), re.IGNORECASE)
>>> insensitive_hippo.sub('giraffe', 'I want a hIPpo for my birthday')
'I want a giraffe for my birthday'
Answer from Blair Conrad on Stack OverflowThe string type doesn't support this. You're probably best off using the regular expression sub method with the re.IGNORECASE option.
>>> import re
>>> insensitive_hippo = re.compile(re.escape('hippo'), re.IGNORECASE)
>>> insensitive_hippo.sub('giraffe', 'I want a hIPpo for my birthday')
'I want a giraffe for my birthday'
import re
pattern = re.compile("hello", re.IGNORECASE)
pattern.sub("bye", "hello HeLLo HELLO")
# 'bye bye bye'
Replacing Text in a Text File - Case Sensitivity
case sensitive string replacement in Python - Stack Overflow
regex - Case-insensitive string replacement in python - Stack Overflow
Case insensitivity in Python strings - Stack Overflow
If I have a text file(let's say names.txt) that has a ton of names in it, if I want to replace all versions of a name I input how do I get it to ignore the case insensitivity? Example: I have Sarah in the document as Sarah, SARAH, SaRah, and sarah. How do I replace all with Mike without having to individually input all versions for replacement? Here's what I've written so far:
find_text = input("enter the word you want to find in this file: ")
replace_text = input("enter the word you want to use as a replacement: ")
with open(r'names.txt', 'r') as file:data = file.read()
if find_text in data:
print('Your text has been replaced')
else:
print('Your initial search term was not found, unable to replace this text')
data = data.replace(find_text, replace_text)
with open(r'names.txt', 'w') as file:
file.write(data)
from string import maketrans
"Abc".translate(maketrans("abcABC", "defDEF"))
Expanding on Mark Byers' answer, Here's a solution which works for replacement text of any length.
The trick is to send a function to re.sub().
import re
def case_sensitive_replace(string, old, new):
""" replace occurrences of old with new, within string
replacements will match the case of the text it replaces
"""
def repl(match):
current = match.group()
result = ''
all_upper=True
for i,c in enumerate(current):
if i >= len(new):
break
if c.isupper():
result += new[i].upper()
else:
result += new[i].lower()
all_upper=False
#append any remaining characters from new
if all_upper:
result += new[i+1:].upper()
else:
result += new[i+1:].lower()
return result
regex = re.compile(re.escape(old), re.I)
return regex.sub(repl, string)
print case_sensitive_replace("abc Abc aBc abC ABC",'abc','de')
print case_sensitive_replace("abc Abc aBc abC ABC",'abc','def')
print case_sensitive_replace("abc Abc aBc abC ABC",'abc','defg')
Result:
de De dE de DE
def Def dEf deF DEF
defg Defg dEfg deFg DEFG
Add \b to the start and end of the keyword:
pattern = re.compile("\\b" + re.escape(old) + "\\b",re.I)
\b means word boundary, and it matches the empty string at the start and end of a word (defined by sequence of alphanumeric or underscore character). (Reference)
As @Tim Pietzcker pointed out, it won't work as you might think if there are non-word (not alphanumeric and not underscore) characters in the keyword.
Put \b at the beginning and ending of the regex.
You can supply the flag re.IGNORECASE to functions in the re module as described in the docs.
matcher = re.compile(myExpression, re.IGNORECASE)
Using re is the best solution even if you think it's complicated.
To replace all occurrences of 'abc', 'ABC', 'Abc', etc., with 'Python', say:
re.sub(r'(?i)abc', 'Python', a)
Example session:
>>> a = 'abc asd Abc asd ABCDE XXAbCXX'
>>> import re
>>> re.sub(r'(?i)abc', 'Python', a)
'Python asd Python asd PythonDE XXPythonXX'
>>>
Note how embedding (?i) at the start of the regexp makes it case insensitive. Also note the r'...' string literal for the regexp (which in this specific case is redundant but helps as soon as you use a regexp that has backslashes (\) in them.