quick regex question

Oliver Fromme olli at haluter.fromme.com
Fri Oct 29 13:34:26 EDT 2004


Peter Otten <__peter__ at web.de> wrote:
 > Steven Bethard wrote:
 > > Matt Price <matt.price <at> utoronto.ca> writes:
 > > > this is surely trivial, but can'f figure it out.  I wnat to replace:
 > > > 
 > > > 'string with spaces'
 > > > with
 > > > 'StringWithSpaces'
 > > 
 > > I know you asked for a regex solution, but I thought I'd drop this
 > > suggestion anyway (not everything really merits a regex) =)
 > 
 > I second that :-)

Me too.  :-)

 > > >>> string1 = 'string with spaces'
 > > >>> ''.join([s.title() for s in string1.split()])
 > > 'StringWithSpaces'
 > 
 > Or, without the list comprehension:
 > 
 > >>> "".join("string with spaces".title().split())
 > 'StringWithSpaces'
 > 
 > > Clear, concise, and uses in the builtin str.title method, which appears to
 > > do exactly what you want.

Uhm, I think the following is more efficient:

>>> "string with spaces".title().replace(" ", "")
'StringWithSpaces'

It doesn't split into a temporary list of strings which
are then joined together again.  Also, I believe it's more
readable than the split/join approach.

Best regards
   Oliver

-- 
Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany

``All that we see or seem is just a dream within a dream.''
(E. A. Poe)



More information about the Python-list mailing list