[Tutor] Splitting at a capital letter in a string

Kent Johnson kent_johnson at skillsoft.com
Sat Oct 30 18:14:32 CEST 2004


You can use a "positive lookbehind assertion" to avoid matching the first 
letter of the string. This says, match any capital letter that is preceded 
by any character:
 >>> import re
 >>> s='HiImAStringWithCaps'
 >>> re.sub(r'(?<=.)([A-Z])', r' \1', s)
'Hi Im A String With Caps'

If you really want to split the string, use re.findall:
 >>> re.findall('[A-Z][^A-Z]*', s)
['Hi', 'Im', 'A', 'String', 'With', 'Caps']

Kent

At 08:14 PM 10/29/2004 -0700, Bill Campbell wrote:
>On Fri, Oct 29, 2004, Douglas N. Shawhan wrote:
> >Is there a way to use the string module to split a string at a capital,
> >so that:
> >
> >HiImAStringWithCaps
> >
> >is rendered
> >
> >Hi Im A String With Caps
> >
> >I looked at the re module, and it looks as if it could be used for such
> >shenannigans...
>
>One way to do this would be:
>
>import re
>pat = re.compile('([A-Z])')
>s = pat.sub(r' \1', 'HiImAStringWithCaps').strip()
>
>The strip call gets rid of the first blank inserted.
>
>Bill
>--
>INTERNET:   bill at Celestial.COM  Bill Campbell; Celestial Systems, Inc.
>UUCP:               camco!bill  PO Box 820; 6641 E. Mercer Way
>FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676
>URL: http://www.celestial.com/
>
>Democracy must be sometihng more than two wolves and a sheep voting on what
>to have for dinner -- James Bovard
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list