String manipulation questions

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • goldtech

    String manipulation questions

    Hi,

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

    ....
    while line:
    counter=counter +1
    if line.find(newst ring) != -1:
    print 'match at line'+str(count er)
    newline = line.replace(ol dstring, newstring)
    fileOUT.write(n ewline)
    line=fileIN.rea dline()
    .....

    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(news tring) != -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.
  • Duncan Booth

    #2
    Re: String manipulation questions

    goldtech <goldtech@world post.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(news tring) != -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(fileI N):
    newline = line.replace(ol dstring, newstring)
    if newline != line:
    print 'match at line', counter+1
    fileOUT.write(n ewline)

    Comment

    • goldtech

      #3
      Re: String manipulation questions

      snip...
      >
      for counter, line in enumerate(fileI N):
      newline = line.replace(ol dstring, newstring)
      if newline != line:
      print 'match at line', counter+1
      fileOUT.write(n ewline)
      "enumerate" - haven't seen that before. Nice!

      Thanks

      Comment

      Working...