stupid newbie question about string and re

Duncan Booth duncan at
Fri Jan 18 10:12:03 EST 2002

bergeston at (Bertrand Geston) wrote in
news:df3b00ed.0201180632.2a93fe17 at 

> after import re and string, I do that:
>>>> re.sub('( (.))',string.upper('\\2'),"I feel really stupid")
> and I received that:
> 'Ifeelreallystupid'
> I want that:
> 'IFeelReallyStupid (or even "IFeelSmart" ... but that is another story
> :-) 
> Where is the mistake please ?

The uppercase form of '\\2' is still '\\2'. You want to uppercase the 
actual match, not the template for the match. The way to do this is to pass 
in a function instead of a string as the replacement.
re.sub('( (.))',lambda match:,"Not so stupid")

Or probably clearer:
def upperCaseGroup2(match):
re.sub('( (.))',upperCaseGroup2,"Not so stupid")

You might also prefer to use '\\b.' as the pattern and group 0. That way 
you get to uppercase any letter at the start of a word, not just those 
preceded by a space.

re.sub('\\b.', lambda match:, 'not stupid at all')

Duncan Booth                                             duncan at
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?

More information about the Python-list mailing list