-1

Target: Remove '\x' from string.

split(), strip(), and replace() all give the same error.

Can anyone help me out?

my_list = '\x00\x06\x00'
my_list.replace('\x', '')
ValueError: invalid \x escape
Jab
  • 26,853
  • 21
  • 75
  • 114
  • 2
    The errors are because it thinks you are trying to remove _part_ of a character. These characters in the string look like hex codes, so `\x00` and `\x06` are single characters. You can't remove the `\x` from them, but you can replace `\x00` with another character. – Mick Sep 12 '18 at 12:36
  • `'\x'` is not a string. `r'\x'` is, but then it is not in `my_list` so after removing it you will have the same string. Is `''.join(format(ord(x), '0>2d') for x in my_list)` what you want? Why is a string assigned to a variable called `my_list`? I am under the impression that you are trying to solve the wrong problem. – Stop harming Monica Sep 12 '18 at 13:07

2 Answers2

1

The default string literal in Python considers backslash as an escape character.

To interpret backslash literally, use r'my string with \x in it', so try:

my_list.replace(r'\x', '')

https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

What exactly do "u" and "r" string flags do, and what are raw string literals?

Tyler Gannon
  • 872
  • 6
  • 19
0

You need to put an r before the '\x' in replace() as well as the string. That will tell python that \ should be interpreted as a character and not as an escape character.

my_list = r'\x00\x06\x00'
my_list.replace(r'\x', '')
Jones1220
  • 786
  • 2
  • 11
  • 22