import string str = "xe7xbdxaaxe6x81xb6xe7x8ex8bxe5x86xa0/xe7x94xb2xe9x93x81xe5x9fx8exefxbcx88xe5xbex90xe6xa2xa6xe5x9cx86Remixxefxbcx89" res = "" for i, ch in enumerate(str): if ch =='x' and len(str) > i+2 and all(c in string.hexdigits for c in str[i+1: i+3]): res += "\\x" else: res += ch print(res)