import re pattern = r"X0+(?=X)"s = "001000X00X001X00X" print(re.sub(pattern, lambda x: x.group().replace('0', '2'), s))
Standard input is empty
001000X22X001X22X
The brand new service which powers Ideone!
Widget for compiling and running the source code in a web browser!