stupid newbie question about string and re

Quinn Dunkan quinn at hork.ugcs.caltech.edu
Sat Jan 19 01:28:48 CET 2002


On Fri, 18 Jan 2002 15:12:03 +0000 (UTC), Duncan Booth
<duncan at NOSPAMrcp.co.uk> wrote:
>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")

Or clearer:

s = 'I feel really smart'
s.title().replace(' ', '')



More information about the Python-list mailing list