What's the easiest way to do a case-insensitive str.replace
in Python?
views:
1255answers:
2
+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
2009-05-28 03:39:13
+13
A:
import re
pattern = re.compile("hello", re.IGNORECASE)
pattern.sub("bye", "hello HeLLo HELLO")
# 'bye bye bye'
Unknown
2009-05-28 03:41:04
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
2009-05-28 18:56:56
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
2009-05-29 19:37:08
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
2009-05-29 20:16:33
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
2010-07-30 00:33:50