Perl s/ To Python?

Gary Wilson Jr gdub at ece.utexas.edu
Fri Jun 10 10:23:08 EDT 2005


John Abel wrote:
> Does anyone know of a quick way of performing this:
> 
> $testVar =~ s#/mail/.*$##g

Use the re (regular expression) module.  Since you are iterating over a lot of
entries, it is good to compile the regular expression outside of the loop.

>>> import re
>>> mailRE = re.compile('/mail/.*$')
>>>
>>> myList = ['/var/mail/joe', '/var/spool/mail/bob']
>>> remainderList = []
>>>
>>> for testVar in myList:
...     remainderList.append(mailRE.sub('', testVar))
...
>>> print '\n'.join(remainderList)
/var
/var/spool





More information about the Python-list mailing list