[issue44773] case_insensitive kwarg in str.replace()

Raymond Hettinger report at bugs.python.org
Thu Jul 29 17:29:38 EDT 2021


Raymond Hettinger <raymond.hettinger at gmail.com> added the comment:

I don't think this should be done.  

If case doesn't matter at all, the input can be casefolded before the replacement:

  s.casefold().replace('hippo', 'giraffe').  

If it can't be casefolded in advance because the case actually matters, then ​it doesn't make sense to mix a case-insensitive search step with a case-sensitive replacement.

Presumably if case matters at all in the original string, then the new text would need to match the case of the old text.  With the example in the selected StackOverflow answer, we get undesirable output for most of the case variants:

 ​strings = [
    ​'I WANT A HIPPO FOR MY BIRTHDAY!',  # lowercase giraffe doesn't fit
    ​'I want a hippo for my birthday.',  # only makes sense when the case matches
    ​'I Want A Hippo for My Birthday',   # lowercase giraffe doesn't fit
    ​'I want a hIPpo for my birthday',   # desired outcome unknown
 ​]
 ​for s in strings:
     ​print(s.replace('hippo', 'giraffe', case_insensitive=True)

ISTM that every answer in the StackOverflow entry has only a toy examples and wouldn't make sense for real text where case is retained everywhere except for the substitutions.

----------
nosy: +rhettinger

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44773>
_______________________________________


More information about the Python-bugs-list mailing list