13

If I have:

a = "fwd"
b = "\fwd"

how can I ignore the "\" so something like

print(a in b)

can evaluate to True?

5
  • What do you mean by "ignore"? Apr 14, 2016 at 13:01
  • @TigerhawkT3 so b can just be "fwd"
    – Kevin R.
    Apr 14, 2016 at 13:02
  • 2
    There is no backslash character in b. There is a form feed character in b, put there by the escape sequence \f.
    – Martijn Pieters
    Apr 14, 2016 at 13:02
  • 2
    @KevinR.: then don't use ` 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'` or b = r'\fwd'.
    – Martijn Pieters
    Apr 14, 2016 at 13:03
  • This should be a duplicate of stackoverflow.com/questions/4703516 but I am out of close votes for today. Aug 7, 2022 at 10:38

4 Answers 4

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)

0
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

0
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
-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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.