Python Forum

Full Version: help for escape sequences
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I'm new in programming and python.
So I have a question for escape sequences.

If you want to print a backslash, you have to use an escape sequence, right?
print('\\')
Output:
\
But you don't have to use an escape sequence here:
print('Tom\s car')
Output:
Tom\s car
Why?

Thank you for your help :)
Because Python realizes that \s isn't a recognized escape sequence, so it leaves it as is. Using two backslashes clarifies what to do in the case of a recognized escape sequence:

>>> print('tom\s car')
tom\s car
>>> print('tom\n car')
tom
 car
>>> print('tom\\n car')
tom\n car
In the case of \s, the unneeded clarity of \\s doesn't hurt.