Why I need to add 5 backslash on the left if I want to show three of them in Python? How to count the backslash?
# [ ] print "\\\WARNING!///"
print('"\\\\\Warning///"')
Why I need to add 5 backslash on the left if I want to show three of them in Python? How to count the backslash?
# [ ] print "\\\WARNING!///"
print('"\\\\\Warning///"')
You can use a "raw string" by adding r
:
print(r'"\\\Warning///"')
This helps to avoid the backslash's "escape" properties, which python uses to control the use of special characters
Backslash is taken as escape sequence most of the time thus for printing single \
one needs to use \\
according to https://docs.python.org/2.0/ref/strings.html
Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string.
since \W
is not a valid escape sequence, \W
is printed as it is. on the other hand \\
is printed as \
.
so \\\\\W
is printed as \\\W
However, in python 3.6, according to Strings and bytes literals
Changed in version 3.6: Unrecognized escape sequences produce a DeprecationWarning. In some future version of Python they will be a SyntaxError.
So your code might give SyntaxError in future python.
Unlike standard C, any unrecognized escape sequences are left unchanged in python.
>>> print('\test')
' est' # '\t' evaluates to tab + 'est'
>>> print('\\test')
'\test' # '\\' evaluates to literal '\' + 'test'
>>> print('\\\test')
'\ est' # '\\' evaluates to literal '\' + '\t' evaluates to tab + 'est'
>>> print('\\\\test')
'\\test' # '\\' evaluates to literal '\' + '\\' evaluates to literal '\' + 'test'
Actually you should type 2n backslashes to represent n of them, technically. In a strict grammar, backslash is reserved as an escape character and has a special meaning, i.e., it does not represent "backslash". So, we took it from our character set to give it a special meaning then how to represent a pure "backslash"? The answer is represent it in the way newline character is represented, namely '\' stands for a backslash.
And the reason why you get 3 backslashes printed when 5 is typed is: The first 4 of them is interpreted as I said above and when it comes to the fifth one, the interpreter found that there is no definition for '\W' so it treated the fifth backslash as a normal one instead of a escape character. This is an advanced convenience feature of the interpreter and might not be true in other versions of it or in other languages (especially in more strict ones).
\
is used for special characters like '\n'
, '\t'
etc. You should type 2n
or 2n-1
\
for printing n
\
.
>>> print('\warning') # 1 \
\warning
>>> print('\\warning') # 2 \
\warning
>>> print('\\\warning') # 3 \
\\warning
>>> print('\\\\warning') # 4 \
\\warning
>>> print('\\\\\warning') # 5 \
\\\warning
>>> print('\\\\\\warning') # 6 \
\\\warning
>>>