If I have:
a = "fwd"
b = "\fwd"
how can I ignore the "\" so something like
print(a in b)
can evaluate to True?
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)
One way of doing it using raw strings:
>>> a = "fwd"
>>> b = "\fwd"
>>> a in b
False
>>> a = r"fwd"
>>> b = r"\fwd"
>>> a in b
True
The relevant docs
You want to write a letter r to the left of the string as in...
str0 = r"\fwd"
In raw strings, characters are treated literally.
For example, in r"\n" is a black-slash followed by a letter n.
r"\n" does not contain a new-line character.
str1 = r"\n"
\ |
n |
|---|---|
| 92 | 110 |
You can verify this by printing out the underlying numbers with the ordinal function ord().
'\\fwd' [92, 102, 119, 100]
'\\n' [92, 110]
'\n' [10]
'\\n' [92, 110]
Test it yourself:
str0 = r"\fwd"
str1 = r"\n"
str2 = "\n"
str3 = "\\n"
tstrs = [str0, str1, str2, str3]
width = max(len(repr(tstr)) for tstr in tstrs)
for tstr in tstrs:
numbers = list(ord(ch) for ch in tstr)
print(repr(tstr).ljust(4 + width), numbers)
b. There is a form feed character inb, put there by the escape sequence\f.` in the string? Not sure what you mean. Or did you want to actually add a backslash? Then double it (to escape it) or use a raw string literal. I.e.b = '\\fwd'` orb = r'\fwd'.