\ Escape codes in Python

Hello!

Have you ever wondered what \ does? Well you’re gonna know that now!

Newline

The “\n” command creates a new line. It works like this:

print("First Line!\nSecond Line!")

Tab

The “\t” command places the cursor on the position in the line that is the next multiple of 4 (this is on replit, but the number can change based on terminal). You can use it in tables. Here’s an example, printing the times tables:

for i in range(2, 13):
    for j in range(1, 13):
        print(end=f"{i*j}\t")
    print()

Return

The “\r” command puts the cursor at the start of the current line. Here’s an example:

print("hello\rJ")

The output for the code above is Jello

Print a \, ", or '

But what if you want to print a backslash or quote?

You can’t do that:

print("\")

That would throw a SyntaxError. If you wanted to print a backslash, you would have to put two backslashes, like this:

print("\\")

Outputs: \

For quotes use \" or \'.

Reference

Code Description
\n Newline
\t Tab
\r Return without newline
3 Likes

make wiki? (hello there TL4 users)

1 Like

Yeh I want it to be a wiki

Admins can you make this a wiki?

yup, admins and TL4s
:+1:

I would remove the “Outside of strings” section because what you should be doing is relying on the black formatter to split your conditions when they’re too long. black would output

if (
    some_long_rule1
    and some_long_rule2
):

as it is more readable and easy to modify.

1 Like

QwertyQwerty88 added it. You can remove/replace it if you want