Content replacement in python regular parentheses

string original format: 123123
requirements: 1O2O3O1T2T3T1O2O3O
description: add O after characters that are not in parentheses, and T

after characters in parentheses

-sharp -*-coding:utf-8-*-
import re
st='123123123'
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

Menu