16

If I have:

a = "fwd"
b = "\fwd"

how can I ignore the "\" so something like

print(a in b)

can evaluate to True?

4
  • What do you mean by "ignore"? Commented Apr 14, 2016 at 13:01
  • @TigerhawkT3 so b can just be "fwd" Commented 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. Commented 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'. Commented Apr 14, 2016 at 13:03

4 Answers 4

30

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)

Sign up to request clarification or add additional context in comments.

Comments

16

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

Comments

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

Comments

0

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.