13

If I have:

a = "fwd"
b = "\fwd"

how can I ignore the "\" so something like

print(a in b)

can evaluate to True?

Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42
Kevin R.
  • 572
  • 2
  • 5
  • 15

4 Answers4

26

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)

jfs
  • 399,953
  • 195
  • 994
  • 1,670
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
15

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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
jDo
  • 3,962
  • 1
  • 11
  • 30
1

You need to "escape" the backslash, as in:

b = '\\fwd'

Otherwise, it reads the single backslash + f as an ASCII character (a formfeed).

Here's an example.

>>> a='fwd'
>>> b='\fwd'
>>> c='\\fwd'
>>> a in b
False
>>> a in c
True
rajah9
  • 11,645
  • 5
  • 44
  • 57
-1

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)
Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42