Case insensitive replacement?
MRAB
python at mrabarnett.plus.com
Tue Sep 27 13:10:50 EDT 2016
On 2016-09-27 17:56, Tim Chase wrote:
> 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):]
> )
>
The disadvantage of your "string-hacking" is that you're assuming that
the uppercase version of a string is the same length as the original:
That's not always the case:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64
bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> '\N{LATIN SMALL LETTER SHARP S}'
'ß'
>>> '\N{LATIN SMALL LETTER SHARP S}'.upper()
'SS'
>>>
> 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=""
>
More information about the Python-list
mailing list