Newbie seeks help on case preserving substitutions

Carel Fellinger cfelling at iae.nl
Mon Jun 25 18:56:49 EDT 2001


Nicola Musatti <objectway at divalsim.it> wrote:
...
> What I'm currently doing is search for the first string ignoring case,
> and substitute the second character by character according to the first
> string's case:

that seems reasonable, but your code could be simplified, like:


### replace strings, preserving case
import re

class PreserveCase:
    def __init__(self, new):
        self.new = new

    def __call__(self, match_obj):
        old = match_obj.group()
        new = list(self.new)
        for i in range(len(old)):
            if old[i].isupper():
                new[i] = new[i].upper()
        return "".join(new)


oldFile = '''
ECBASE
ECBase
ecbase
'''

newFile = '''
OWTEST
OWTest
owtest
'''

substituter = re.compile(r"ecbase", re.IGNORECASE).sub

assert newFile == substituter(PreserveCase("owtest"), oldFile)

### now you could do things like:
#
#   oldFile = open("oldFile").read()
#   newFile = open("newFile", "w")
#   newFile.write(substituter(PreserveCase("owtest"), oldFile))
-- 
groetjes, carel



More information about the Python-list mailing list