[Tutor] simple text replace

j booth j8ooth at gmail.com
Sun Jul 26 22:33:19 CEST 2009


Hello,

I am scanning a text file and replacing words with alternatives. My
difficulty is that all occurrences are replaced (even if they are part of
another word!)..

This is an example of what I have been using:

    for line in fileinput.FileInput("test_file.txt",inplace=1):
>         line = line.replace(original, new)
>         print line,
>         fileinput.close()


original and new are variables that have string values from functions..
original finds each word in a text file and old is a manipulated
replacement. Essentially, I would like to replace only the occurrence that
is currently selected-- not the rest. for example:

python is great, but my python knowledge is limited! regardless, I enjoy
> pythonprogramming


returns something like:

snake is great, but my snake knowledge is limited! regardless, I enjoy
> snakeprogramming


thanks so much!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090726/56e0c2b1/attachment-0001.htm>


More information about the Tutor mailing list