1

The general problem is that I need the hexadecimal string stays in that format to assign it to a variable and not to save the coding?

no good:

>>> '\x61\x74'
'at'
>>> a = '\x61\x74'
>>> a
'at'

works well, but is not as:

>>> '\x61\x74'
'\x61\x74' ????????
>>> a = '\x61\x74'
>>> a
'\x61\x74' ????????
user987055
  • 1,039
  • 4
  • 14
  • 25

2 Answers2

4

Use r prefix (explained on SO)

a = r'\x61\x74'
b = '\x61\x74'
print (a) #prints  \x61\x74
print (b) # prints at
Community
  • 1
  • 1
J0HN
  • 26,063
  • 5
  • 54
  • 85
3

It is the same data. Python lets you specify a literal string using different methods, one of which is to use escape codes to represent bytes.

As such, '\x61' is the same character value as 'a'. Python just chooses to show printable ASCII characters as printable ASCII characters instead of the escape code, just because that makes working with bytestrings that much easier.

If you need the literal slash, x character and the two digit 6 and 1 characters (so a string of length 4), you need to double the slash or use raw strings.

To illustrate:

>>> '\x61' == 'a'  # two notations for the same value
True
>>> len('\x61')    # it's just 1 character
1
>>> '\\x61'        # escape the escape
'\\x61'
>>> r'\x61'        # or use a raw literal instead
'\\x61'
>>> len('\\x61')   # which produces 4 characters
4
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343