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?
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?
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]))
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
You need \\x because \ used for escape the characters :
>>> s='\\x'+'a'
>>> print s
\xa
Try to make a raw string as follows:
a = r'\x'+''.join(lstDES[100][:2]) + r'\x'+''.join(lstDES[100][2:])