[Tutor] string replacement puzzlement
Thu, 25 Jan 2001 21:38:00 -0600
Okay, I'm stumped, and if anyone can de-stump me a bit, you'll have my
I'm trying to get the hang of replacing strings within a specified file,
which I've managed to do with some success. However, my next move was
to start trying to replace multiple items within the same file in one
fell swoop. The following example is one of my attempts to do so, and
the results were less than impressive. In my sample file, containing a
random collection of punctuation marks, some replacement happened, but
in each case, the original symbols were left behind, and the "?"
replacement just didn't happen. (And I know the code is a kludge, but
it looked a bit more elegant about 42 changes ago.)
I've also tried other ways, such as telling it to open and close the
files for each operation, but to no particular avail.
inputfile = open('c:\windows\desktop\\inputfile.txt', 'r')
outputfile = open('c:\windows\desktop\\outputfile.txt', 'w')
outputfile.write(inputfile.read().replace("!", "exclamation point"))
outputfile.write(inputfile.read().replace("?", "question mark"))
I don't know of a way to use replace() with multiple replacements as
arguments, but it's what I had in mind before I started adding all this
Visit the Useless Python Repository!