re

Peter Otten __peter__ at web.de
Fri Jan 2 16:02:32 EST 2004


Maxim Khesin wrote:

> I am studying the re module and still do not understand how to do some
> really simple tasks:
> 1) say I need to capitalize any word that is between the words 'United'
> and  'of America'. So I do

With the help of A. M. Kuchling's Regular Expression Howto:

>>> import re
>>> sample = " ".join(["United %s of America" % s for s in "birds                                  
states rocks".split()])
>>> r = re.compile("(United )(.*?)(of America)")
>>> def fun(m):
...     return m.group(1) + m.group(2).capitalize() + m.group(3)
...
>>> r.sub(fun, sample)
'United Birds of America United States of America United Rocks of America'
>>> sample
'United birds of America United states of America United rocks of America'
>>>

Disclaimer: I'm no regexpert, so there may be simpler solutions.

Peter




More information about the Python-list mailing list