Multi-line Strings

String Formatting

Multi-line Strings

In this tutorial, we'll create longer messages across several lines.

Sometimes you need text across several lines.

You can use \n:

message = "Line one\nLine two"
print(message)

You can also use triple quotes:

message = """Line one
Line two
Line three"""

print(message)

Multi-line f-strings

Triple-quoted strings can be f-strings too:

name = "Ada"
score = 95

report = f"""
Student: {name}
Score: {score}
Passed: {score >= 50}
"""

print(report)

This is useful for simple reports or longer messages.

Watch the Extra Newlines

Triple-quoted strings include the line breaks you type. This can add blank lines at the start or end.

If that matters, keep the text tight:

report = f"""Student: {name}
Score: {score}"""

When to Use Multi-line Strings

Use them for:

  • Simple reports
  • Email-style messages
  • Long instructions
  • Text you plan to write to a file

For short messages, a normal f-string is usually clearer.

Combining With Files

Multi-line strings are useful when writing reports to files:

name = "Ada"
score = 95

report = f"""Name: {name}
Score: {score}
"""

with open("report.txt", "w") as file:
    file.write(report)

The string is built first, then written to the file.

Practice

Create a multi-line f-string that shows a username, level, and points total.