By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,272 Members | 1,733 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,272 IT Pros & Developers. It's quick & easy.

String manipulation questions

P: n/a
Hi,

Replacing strings in a text (likely an XML) file. Some newbie
questions...

....
while line:
counter=counter+1
if line.find(newstring) != -1:
print 'match at line'+str(counter)
newline = line.replace(oldstring, newstring)
fileOUT.write(newline)
line=fileIN.readline()
.....

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.

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?
Thanks

P.S. I know I should be using XSLT to transform XML - but the above
seems to work for small text changes.
Apr 9 '08 #1
Share this Question
Share on Google+
2 Replies


P: n/a
goldtech <go******@worldpost.comwrote:
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)
Apr 9 '08 #2

P: n/a
snip...
>
for counter, line in enumerate(fileIN):
newline = line.replace(oldstring, newstring)
if newline != line:
print 'match at line', counter+1
fileOUT.write(newline)
"enumerate" - haven't seen that before. Nice!

Thanks
Apr 9 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.