stupid newbie question about string and re

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Jan 18 16:12:03 CET 2002


bergeston at yahoo.fr (Bertrand Geston) wrote in
news:df3b00ed.0201180632.2a93fe17 at posting.google.com: 

> 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.
Try:
re.sub('( (.))',lambda match: match.group(2).upper(),"Not so stupid")

Or probably clearer:
def upperCaseGroup2(match):
    	return match.group(2).upper()
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: match.group(0).upper(), 'not stupid at all')

-- 
Duncan Booth                                             duncan at rcp.co.uk
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