0
0
PythonHow-ToBeginner · 3 min read

How to Create Multiline Strings in Python Easily

In Python, you can create a multiline string by enclosing the text within triple quotes, either ''' or """. This allows the string to span multiple lines exactly as written in the code.
📐

Syntax

Use triple quotes to start and end a multiline string. You can use either ''' or """. Everything between these quotes, including line breaks and spaces, becomes part of the string.

python
multiline_string = '''This is a string
that spans multiple
lines.'''

print(multiline_string)
Output
This is a string that spans multiple lines.
💻

Example

This example shows how to create a multiline string and print it exactly as it appears, preserving line breaks and spaces.

python
poem = """Roses are red,
Violets are blue,
Python is fun,
And so are you."""

print(poem)
Output
Roses are red, Violets are blue, Python is fun, And so are you.
⚠️

Common Pitfalls

One common mistake is to try to break a string across lines without using triple quotes, which causes a syntax error. Another is forgetting that triple quotes preserve all whitespace, including indentation, which might add unwanted spaces.

python
# Wrong way - causes error
# text = 'This is a string
# that breaks lines'  # SyntaxError

# Right way
text = '''This is a string
that breaks lines'''
Output
This is a string that breaks lines
📊

Quick Reference

MethodDescriptionExample
Triple quotesCreate multiline string preserving line breaks'''Line1 Line2'''
Backslash (legacy)Use backslash to continue string on next line without newline'Line1\ Line2'

Key Takeaways

Use triple quotes (''' or """) to write multiline strings easily.
Triple-quoted strings keep all line breaks and spaces exactly as typed.
Avoid breaking strings across lines without triple quotes to prevent errors.
Indentation inside triple quotes is preserved and can affect the string content.
Backslash can continue a string on the next line but does not add a newline.