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 -- https://mail.python.org/mailman/listinfo/python-list