[Tutor] capitalize() but only first letter

Erik Price eprice@ptc.com
Fri Feb 7 10:45:02 2003


Magnus Lycka wrote:

> Use regular expressions (RE).
> 
>  >>> import re
>  >>> def upper(matchobj):
> ...     return matchobj.group(0).upper()
> ...
>  >>> re.sub(r'\b\w', upper, 'thIs is a stRiNG wiTh miXed cAsEs')
> 'ThIs Is A StRiNG WiTh MiXed CAsEs'

[...]

> re.sub(pattern, whatToSubstituteWith, aString)
> 
> re.sub stands for substitute, so re.sub(r'\b\w', 'X', 'hi there')
> would return 'Xi Xhere'. But instead of a string to substitute
> with, we can supply a function.
> 
> This function will be fed with a RE match object for each RE
> match in the string. In this case the first character in each
> word.

I'm not sure I understand why this works.  As I understand it, you're 
saying:

1. The re.sub() function accepts a string as its second argument
2. The re.sub() function will also accept a function name as its second 
argument
3. If the re.sub() function is passed a function name as its second 
argument, it will call that function and pass it a match object 
argument.  Is there some kind of internal type checking done to 
determine if the argument is a string or a function name, or is this 
some esoteric feature of Python that I've never heard of at work?


Erik