Triple Quotes in Python: Multi-Line Strings
Write Text Over Many Lines
With \n you can print several lines, but long text full of \n is hard to read. Python has an easier way: triple quotes.
Put three quote marks at the start and three at the end. Then just press Enter wherever you want a new line:
print("""Roses are red,
Violets are blue,
Python is fun,
And so are you!""")Roses are red, Violets are blue, Python is fun, And so are you!
What you see in the code is what you get on the screen. No \n needed.
Three single or three double quotes
Both work the same, just like normal strings:
print('''Line 1
Line 2''')
print("""Line 3
Line 4""")Line 1 Line 2 Line 3 Line 4
Start and end with the same kind: ''' with ''', or """ with """.
Everything is kept, even spaces
Triple quotes keep your text exactly as you typed it, including spaces at the start of a line:
print("""Menu:
- Tea
- Coffee""")Menu: - Tea - Coffee
That's handy for lists and art. But be careful: if you add spaces by accident, they get printed too.
Common beginner doubt: "Can I still use \n and \t inside triple quotes?" Yes! Escape sequences work in every kind of string.
\n or triple quotes?
Both make several lines, so which one should you use?
- For two or three short lines,
\nis quick:print("Yes\nNo"). - For longer text, like a poem, a menu or instructions, triple quotes are easier to read and to change later, because the code looks like the output.
There's no wrong choice. Pick the one that makes your code easiest to read.
Triple quotes print text exactly as you typed it, over as many lines as you like.