change the first letter into uppercase (ask)
MRAB
python at mrabarnett.plus.com
Sat Oct 20 19:43:42 EDT 2012
On 2012-10-21 00:14, contro opinion wrote:
> the pattern `re.compile(".(?#nyh2p){0,1}")` , make me confused,
> can you explain how it can match the first letter of every word?
>
It matches all of the characters, plus an empty string at the end. It's
equivalent to:
result = ""
for c in "a test of capitalizing":
result = (result + c).title()
result = (result + "").title()
or:
result = "a test of capitalizing".title()
but somewhat slower...
>
> 2012/10/20 Dennis Lee Bieber <wlfraed at ix.netcom.com
> <mailto:wlfraed at ix.netcom.com>>
>
> On Sat, 20 Oct 2012 01:03:46 -0400, Zero Piraeus <schesis at gmail.com
> <mailto:schesis at gmail.com>>
> declaimed the following in gmane.comp.python.general:
>
> > :
> >
> > On 20 October 2012 00:09, contro opinion <contropinion at gmail.com
> <mailto:contropinion at gmail.com>> wrote:
> > > how can i use regular expression in python to change the string
> > > "a test of capitalizing"
> > > into
> > > "A Test Of Capitalizing"?
> >
> > >>> import re
> > >>> pattern = re.compile(".(?#nyh2p){0,1}")
> > >>> result = ""
> > >>> f = str.title
>
> f = str.capitalize
>
> > >>> for match in re.findall(pattern, "a test of capitalizing"):
> > ... result = f(result + match)
>
> result = result + f(match)
>
> Or closer... Don't both with f and str.capitalize
>
> result = result + match.capitalize()
>
> > ...
> > >>> print(result)
> > A Test Of Capitalizing
> > >>>
> >
>
>
> >>> "a test of capitalizing".title()
> 'A Test Of Capitalizing'
> >>>
>
> Not to be confused with
>
> >>> "a test of capitalizing".capitalize()
> 'A test of capitalizing'
> >>>
>
More information about the Python-list
mailing list