[Tutor] search and replace

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Mar 7 09:13:07 CET 2006



> I have a problem finding specific words.
> I would like to filter out a word or replace it in a file.
> I notices that the re module is good for finding patterns.

Hi Tak,

Although regular expressions might be overkill for this problem, it can't
hurt to know about the Regex HOWTO:

    http://www.amk.ca/python/howto/regex/


Note that strings can already do simple replacement:

######
>>> 'this is a test hi world'.replace('hi', 'hello')
'thellos is a test hello world'
######

As this example shows, we need to be a bit careful with it.


Regexes allow us to do a slightly smarter, word boundary-specific
substitution:

######
>>> import re
>>> re.sub(r'\bhi\b', 'hello', 'this is a test hi world')
'this is a test hello world'
######

The Regex HOWTO link above is a tutorial on how to use the module
effectively.  If you have questions, please feel free to bring them up.

Good luck!



More information about the Tutor mailing list