views:

1255

answers:

2

What's the easiest way to do a case-insensitive str.replace in Python?

+18  A: 

The string type doesn't support this. You're probably best off using the regular expression sub method with the re.IGNORECASE option.

>>> import re
>>> insensitive_hippo = re.compile('hippo', re.IGNORECASE)
>>> insensitive_hippo.sub('giraffe', 'I want a hIPpo for my birthday')
'I want a giraffe for my birthday'
Blair Conrad
+13  A: 
import re
pattern = re.compile("hello", re.IGNORECASE)
pattern.sub("bye", "hello HeLLo HELLO")
# 'bye bye bye'
Unknown
Please vote for this one. I had the first working example, and Blair copied me badly while everyone voted him up. See his edits.
Unknown
I don't really want to start something here, but I would like to explain. I didn't copy the example badly. I noticed that I'd not paid attention when I put my first example in and so I fixed it. That being said, please with vote your hearts - unaccept my answer, vote it down, and/or vote @Unknown's up based on the answers' merits - or just ignore the whole thing. After all, I think we all just want the questioners to get satisfactory answers.
Blair Conrad
The thing is that whoever gets an answer up fastest (no matter if it was correct or not) seems to get upvoted. Do you really want to encourage the people giving the correct answers to leave Stack Overflow?
Unknown
If they are more concerned about themselves than the people they are supposed to be helping, then yes: we should encourage such people to leave Stack Overflow regardless of whether or not they are giving the right answers.
Noctis Skytower