This one is a bit tricky I think.
if I have:
a = "fwd"
b = "\fwd"
how can I ignore the "\" so something like
print(a in b)
can evaluate to True?
To do this, simply add a backslash ( \ ) before the character you want to escape.
The first two backslashes ( \\ ) indicate that you are escaping a single backslash character. The third backslash indicates that you are escaping the double-quote that is part of the string to match.
To ignore all the escape sequences in the string, we have to make a string as a raw string using 'r' before the string. After that escape sequence will also be considered normal characters.
In Python strings, the backslash “ ” is a special character, also called the “escape” character. It is used in representing certain whitespace characters: “\t” is a tab, “\n” is a new line, and “\r” is a carriage return. Finally, “ ” can be used to escape itself: “\” is the literal backslash character.
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:[...]
\fASCII Formfeed (FF)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With