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?

2
  • 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. Commented Aug 7, 2022 at 3: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 minimal reproducible example first. Commented Aug 7, 2022 at 3:25

4 Answers 4

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]))
Sign up to request clarification or add additional context in comments.

1 Comment

the last command worked perfectly for me
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

Comments

1

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

>>> s='\\x'+'a'
>>> print s
\xa

Comments

1

Try to make a raw string as follows:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.