tags:

views:

99

answers:

1

Hi All,

I am looking to accomplish the following and am wondering if anyone has a suggestion as to how best go about it.

I have a string, say 'this-is,-toronto.-and-this-is,-boston', and I would like to convert all occurrences of ',-[a-z]' to ',-[A-Z]'. In this case the result of the conversion would be 'this-is,-Toronto.-and-this-is,-Boston'.

I've been trying to get something working with re.sub(), but as yet haven't figured out how how

testString = 'this-is,-toronto.-and-this-is,-boston'
re.sub(r',_([a-z])', r',_??', testString)

Thanks!

+11  A: 

re.sub can take a function which returns the replacement string:

import re

s = 'this-is,-toronto.-and-this-is,-boston'
t = re.sub(',-[a-z]', lambda x: x.group(0).upper(), s)
print t

prints

this-is,-Toronto.-and-this-is,-Boston
Ned Batchelder
+1, beat me to it :) Mine matched the whole word and called x.group(0).capitalize, but yours works the same and may be faster.
dwc
Thanks guys! Appreciate the help!
Matty