Newbie seeks help on case preserving substitutions
Nicola Musatti
objectway at divalsim.it
Mon Jun 25 12:32:59 EDT 2001
Hi,
I have a number of files which contain different variations of the same
string, e.g.
ECBASE
ECBase
ecbase
Which I want to substitute with a different string, while preserving the
original case, e.g.
OWTEST
OWTest
owtest
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:
for line in inFile.readlines():
matchRes = re.compile(oldString).search(line)
if matchRes:
found = 1
new = line[:matchRes.start()]
for i in range(matchRes.start(),matchRes.end()):
if line[i] in string.uppercase:
new = new + string.upper(newString[i-matchRes.start()])
else:
new = new + string.lower(newString[i-matchRes.start()])
new = new + line[matchRes.end():]
I was wondering if there's a more compact way to do what I want.
Thanks,
Nicola Musatti
More information about the Python-list
mailing list