1

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
  • 114,268
  • 16
  • 167
  • 218
user1914367
  • 171
  • 1
  • 2
  • 12
  • It turned out, based on the comments, that what OP actually wanted to do is not at all what is described here. The goal was actually to interpret the `lstDES[100][:2]` text as representing a character code in hexadecimal. It's not possible to just stick a backslash and a lowercase x in front of that text and get that effect; some explicit interpretation would be required. – Karl Knechtel Aug 07 '22 at 03:18
  • I ended up changing the duplicate link to something completely different on that basis - it was hard to find the right one. This is why it's important to clarify questions and get a proper [mre] first. – Karl Knechtel Aug 07 '22 at 03:25

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
  • 1,048,767
  • 296
  • 4,058
  • 3,343
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
  • 51,807
  • 15
  • 147
  • 125
1

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

>>> s='\\x'+'a'
>>> print s
\xa
Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

Try to make a raw string as follows:

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