Search code examples
pythonescapingbackslash

ignoring backslash character in python


If I have:

a = "fwd"
b = "\fwd"

how can I ignore the "\" so something like

print(a in b)

can evaluate to True?


Solution

  • You don't have fwd in b. You have wd, preceded by ASCII codepoint 0C, the FORM FEED character. That's the value Python puts there when you use a \f escape sequence in a regular string literal.

    Double the backslash if you want to include a backslash or use a raw string literal:

    b = '\\fwd'
    b = r'\fwd'
    

    Now a in b works:

    >>> 'fwd' in '\\fwd'
    True
    >>> 'fwd' in r'\fwd'
    True
    

    See the String literals documentation:

    Unless an 'r' or 'R' prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C. The recognized escape sequences are:

    [...]

    \f ASCII Formfeed (FF)