fork download
  1. import re
  2.  
  3. strings = [
  4. "0X001000X00X001X00X0",
  5. "001000X00X001X00X",
  6. "000X000",
  7. "000"
  8. ]
  9.  
  10. pattern = r"(?:X0+|^0+)(?=X|$)"
  11.  
  12. for s in strings:
  13. print(re.sub(pattern, lambda x: x.group().replace('0', '2'), s))
Success #stdin #stdout 0.03s 9564KB
stdin
Standard input is empty
stdout
2X001000X22X001X22X2
001000X22X001X22X
222X222
222