quick regex question

Robert Brewer fumanchu at amor.org
Thu Oct 28 13:22:24 EDT 2004


Matt Price wrote:
> this is surely trivial, but can'f figure it out.  I wnat to replace:
> 
> 'string with spaces'
> with
> 'StringWithSpaces'
> 
> so I tried this:
> 
> s = 'string with spaces'
> pat = ' (.)'
> t = re.sub(pat, upper, s)
> 
> I know this isn't quite right, I expect it to return:
> 'String With Spaces'

A couple things are tricky about what you want.

1. If you use a function for the replacement arg in re.sub, it receives
a Match object, not the string, so you need to write a function to pull
the matching text out of the Match object:

def up_it(m):
    return m.group(1).upper()

2. Your pattern doesn't address the start of the string. You probably
want "non-grouping" parentheses to handle the "or". 

>>> re.sub(r'(?:^| )(.)', up_it, 'string with spaces')
'StringWithSpaces'


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list