String manipulation questions

Duncan Booth duncan.booth at invalid.invalid
Wed Apr 9 09:32:55 EDT 2008


goldtech <goldtech at worldpost.com> wrote:

> Question1: The replace method - If a string does not have the target
> replacement "newstring", then newline equals oldstring? Ie. oldstring
> is not changed in any way? Seems to be what I observe but just want to
> confirm this.

Yes.

> 
> Question2:  I'm using "line.find(newstring) != -1..."  because I want
> to print when a replacement happens. Does "line.replace..." report
> indirectly somehow when it replaces?

Just do the line.replace() and then test for a change.

Question 3 (which I'm sure you meant to ask really) ...
No, you shouldn't be using a while loop here. Use a for loop and the 
enumerate builtin:

   for counter, line in enumerate(fileIN):
       newline = line.replace(oldstring, newstring)
       if newline != line:
           print 'match at line', counter+1
       fileOUT.write(newline)



More information about the Python-list mailing list