Forum Archive

Python question about case insensitive replacement

cvp

I've a text 'Word word'
How can I replace the string 'word' independantly of its case by itself followed by a another string, exemple 'xxx'
Thus my text should become 'Wordxxx wordxxx'.

If I use

        import re
        my_text = 'Word word'
        src_str  = re.compile('word', re.IGNORECASE) 
        my_text = src_str.sub('wordxxx', my_text)

Result will be 'wordxxx wordxxx', thus I lose original case

I know I could loop on occurrences but if you know an easier way...

Olaf

You can use \1 to refer to matched text grouped by () in the regex. So:
```
import re
my_text = 'Word word'
src_str = re.compile('(word)', re.IGNORECASE)
my_text = src_str.sub(r'\1xxx', my_text)
print(my_text)

cvp

@Olaf Thanks a lot, I didn't know this \1

JanRomero

Thanks for sharing useful post here.
mcdvoice login