ignoring backslash character in python

Question:

If I have:

a = "fwd"
b = "fwd"

how can I ignore the "" so something like

print(a in b)

can evaluate to True?

Asked By: Kevin R.

||

Answers:

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

Answered By: jDo

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
Answered By: rajah9

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)

Answered By: Martijn Pieters

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)
Answered By: Samuel Muldoon
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.