Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ignoring backslash character in python

Tags:

python

This one is a bit tricky I think.

if I have:

a = "fwd"
b = "\fwd"

how can I ignore the "\" so something like

print(a in b)

can evaluate to True?

like image 618
Kevin R. Avatar asked Apr 14 '16 13:04

Kevin R.


People also ask

How do you ignore a special character in Python?

To do this, simply add a backslash ( \ ) before the character you want to escape.

How do I escape a backslash?

The first two backslashes ( \\ ) indicate that you are escaping a single backslash character. The third backslash indicates that you are escaping the double-quote that is part of the string to match.

How do you ignore an escape character?

To ignore all the escape sequences in the string, we have to make a string as a raw string using 'r' before the string. After that escape sequence will also be considered normal characters.

Is backslash a special character in Python?

In Python strings, the backslash “ ” is a special character, also called the “escape” character. It is used in representing certain whitespace characters: “\t” is a tab, “\n” is a new line, and “\r” is a carriage return. Finally, “ ” can be used to escape itself: “\” is the literal backslash character.


1 Answers

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)

like image 160
Martijn Pieters Avatar answered Oct 10 '22 19:10

Martijn Pieters