469,928 Members | 1,844 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,928 developers. It's quick & easy.

String manipulation questions

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
2 1096
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
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.

Similar topics

9 posts views Thread by I. Kobrinsky | last post: by
9 posts views Thread by stefan.oedenkoven | last post: by
15 posts views Thread by Beeeeeves | last post: by
32 posts views Thread by tshad | last post: by
29 posts views Thread by zoro | last post: by
4 posts views Thread by WaterWalk | last post: by
9 posts views Thread by Michael D. Ober | last post: by
5 posts views Thread by Joe Nova | last post: by
4 posts views Thread by chikito.chikito | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.