import re pattern=re.compile(r"(w+)(w+)") string="i say, hello world" def func(m): return m.group(1).title()+''+m.group(2).title() print re.sub(pattern,func,s)