Domanda

here I want to replace # with \x but when I print h it doesn't give me the same result when I print y.decode()

does any one have an explaination and a solution for it ?

    s = "#53ule#69#6dan"
y = "\x53ule\x69\x6dan"
f = s.replace("#","\\x")
print f
h = f.decode()
print h
print y.decode()
È stato utile?

Soluzione

The \x in y is not an actual backslash character followed by an x character, but rather the start of an escape sequence.

The whole sequence "\x53" is "S" (because "S" is 0x53 in ASCII). Similarly, "\x69" is "i" and "\x6d" is "m".

When you do your replace call to compute f, you don't get the escape sequence, but rather an actual backslash character followed by an x character.

I'm not sure there is a completely straight forward way to go from a hex string to a regular one, but this regex substitution will do the trick with some help from int and chr:

re.sub("#(..)", lambda match: chr(int(match.group(1), 16)), s)

Altri suggerimenti

re.sub("#([A-Fa-f0-9]{2})",lambda m:unichr(int(m.groups()[0],16)),"#53ule#69#6dan")

might be what your looking for ...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top