# -*-coding:utf-8-*- import re st='123(123)123' def _rep(matched): if matched.group(1) is None: return re.sub("(\S)",r"\1O",matched.group()) else: return re.sub("(\S)",r"\1T",matched.group(1)) result=re.sub("(([^()]+))|[^()]+",_rep,st) print result