Search code examples
pythonescapingconditional-statementsliteralsstring-literals

How do you conditionally check for an escape character?


I have a string which contains the escape character \x . However if i try to check for it with:

if char == "\x":

I receive the error

ValueError: invalid \x escape

Solution

  • I have a string which contains the escape character \x

    No you don't. There is no such things as "the escape character \x". \x is two characters, not one. The first character is the backslash, the second character is lower-case x.

    You have to escape the backslash in order to defeat its meaning.

    if two_character_string == "\\x":
    

    or perhaps

    if first_char == "\\" and second_char == "x":