Escape Sequences in Python: \n, \t and More
New Lines with \n
So far, every print() shows one line. But what if you want one print() to show several lines? You use a special code inside the text: \n.
print("Line one\nLine two")Line one Line two
\n means new line. It's like pressing Enter in the middle of your text. Everything after it goes to the next line.
What is an escape sequence?
A backslash \ inside a string is special. It tells Python: "the next character is not normal text, it's an instruction". The backslash and the character after it are called an escape sequence. They escape from their normal meaning.
\n is not printed. Python sees it, and starts a new line instead.
As many lines as you like
You can use \n again and again:
print("Sunny\nRocky\nLucky")Sunny Rocky Lucky
One print(), three lines. This keeps short lists and messages in a single line of code.
Common beginner doubt: "Do I need spaces around \n?" No. A space before \n would end up at the end of the first line, and a space after it at the start of the next line. Usually you don't want either.
\n starts a new line, right in the middle of your text.