Case insensitive replacement?

Tim Chase python.list at tim.thechases.com
Tue Sep 27 12:56:38 EDT 2016


I'd like to do a case-insensitive replacement in a string but want to
do it pythonically.  Ideally, the code would something like

  needle = "World"
  haystack = "Hello, world!"
  replacement = "THERE"
  result = haystack.replace(needle, replacement, ignore_case=True)
  # result would be "Hello, THERE!"

As that's not an option, I can do it either with string-hacking:

  try:
    index = haystack.upper().find(needle.upper())
  except ValueError:
    result = haystack
  else:
    result = (
      haystack[:index]
      + replacement
      + haystack[index + len(needle):]
      )

or with regexes:

  import re
  r = re.compile(re.escape(needle), re.I)
  result = r.sub(replacement, haystack)

The regex version is certainly tidier, but it feels a bit like
killing a fly with a rocket-launcher.

Are there other/better options that I've missed?

Also, if it makes any difference, my replacement in this use-case is
actually deletion, so replacement=""

Thanks,

-tkc





 



More information about the Python-list mailing list