2

I would like to make a string that includes "\x" but I get

invalid \x escape

error.

a = '\x'+''.join(lstDES[100][:2])+'\x'+''.join(lstDES[100][2:])

How can I correct it?

Cory Kramer
  • 107,498
  • 14
  • 145
  • 201
user1914367
  • 173
  • 1
  • 2
  • 12

4 Answers4

7

Double the backslash to stop Python from interpreting it as a special character:

'\\x'

or use a raw string literal:

r'\x'

In regular Python string literals, backslashes signal the start of an escape sequence, and \x is a sequence that defines characters by their hexadecimal byte value.

You could use string formatting instead of all the concatenation here:

r'\x{0[0]}{0[1]}\x{0[2]}{0[3]}'.format(lstDES[100])

If you are trying to define two bytes based on the hex values from lstDES[100] then you'll have to use a different approach; producing a string with the characters \, x and two hex digits will not magically invoke the same interpretation Python uses for string literals.

You would use the binascii.unhexlify() function for that instead:

import binascii

a = binascii.unhexlify(''.join(lstDES[100][:4]))
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
1

In Python \ is used to escape characters, such as \n for a newline or \t for a tab.

To have the literal string '\x' you need to use two backslashes, one to effectively escape the other, so it becomes '\\x'.

In [199]: a = '\\x'

In [200]: print(a)
\x
Ffisegydd
  • 47,839
  • 14
  • 137
  • 116
1

You need \\x because \ used for escape the characters :

>>> s='\\x'+'a'
>>> print s
\xa
Mazdak
  • 100,514
  • 17
  • 155
  • 179
1

Try to make a raw string as follows:

a = r'\x'+''.join(lstDES[100][:2]) + r'\x'+''.join(lstDES[100][2:])
Necrolyte2
  • 718
  • 5
  • 12