Replace hello
in Hello World, HELLO PYTHON
with My
.
Since the replace() function replacement is case-sensitive, how can Python implement string replacement without case sensitivity?
仅有的幸福2017-06-28 09:26:52
Reference article: Issues related to Python string operations
String case-insensitive replacementstr.replace(old, new[, max])
The replacement is case-sensitive. Case-insensitive replacement requires the regular expression re.sub(
) with the re.IGNORECASE
option.
>>> import re
>>> reg = re.compile(re.escape('hello'), re.IGNORECASE)
>>> reg.sub('My', 'Hello World, HELLO PYTHON')
'My World, My PYTHON'
阿神2017-06-28 09:26:52
import re
s = 'Hello World, HELLO PYTHON'
print re.sub(r'(?i)hello', 'My', s)