Python Tutorial

How To Format Text in Python 3

Clear, original guide to python string formatting: literals, quotes, escape sequences (\n, \t, \\), triple quotes, raw strings (r""), and examples for formatting text in Python 3.

Drake Nguyen

Founder · System Architect

3 min read
How To Format Text in Python 3
How To Format Text in Python 3

Introduction

This guide explains python string formatting for readable and predictable output. Youll learn how to control quotes, line breaks, indentation, and when to use raw strings or escape sequences so your python strings appear exactly as intended.

Prerequisites

To follow the examples, use Python 3 in a local shell or an editor that runs Python code. Familiarity with basic print statements and variables will help, but no advanced setup is required.

String literals vs string values

A string literal is the text you type in source code, including the surrounding quotes. A string value is the actual characters produced when the program runs (for example, what print() sends to the console). Understanding this distinction is key to effective python string formatting.

Quotes and apostrophes

You can use single or double quotes to define python strings, which makes it easy to include quotes inside text without escaping them. Examples:

print('Sammy says, "Hello!"')
print("Sammy's balloon is red.")

If you need the same kind of quote inside a matching literal, escape it with a backslash:

print("Sammy says, \"Hello!\"")
print('Sammy\'s balloon is red.')

Multiline strings and triple quotes

For longer blocks of text or preserving line breaks, use triple-quoted literals with three single or double quotes. Triple quotes are useful for multi-line docstrings, long messages, or maintaining formatting for poetry and prose.

poem = '''
Roses are red
Violets are blue
'''
print(poem)

Triple-quoted strings often include an extra leading or trailing newline. To avoid that while keeping the source readable, start the literal with a backslash immediately after the opening quotes:

message = """\
This multi-line string
has no leading or trailing blank line
when printed.\
"""
print(message)

Alternatively, remove a stray leading newline with .lstrip('\n'):

text = """
First line
Second line
""".lstrip('\n')
print(text)

Escape sequences (backslash escapes)

Escape sequences let you embed special characters in python strings. Common escape sequences include:

  • \n newline
  • \t tab (horizontal indentation)
  • \\ literal backslash
  • \'\" escaped single or double quote

Examples combining escape characters:

print("This string\nspans multiple\nlines.")
print("1.\tShark\n2.\tShrimp\n10.\tSquid")

Escape sequences are useful for python print newline tab in string scenarios and for controlling layout in console output. For long text where source readability matters, prefer triple-quoted strings over many \n escapes.

Printing backslashes and escape-character lists

To show a backslash in output, escape it twice in a normal string or use a raw string when appropriate:

print("\\")        # prints a single backslash
print("\\n")       # prints backslash and letter n
print(r"C:\\path\\file.txt")  # raw string example showing backslashes literally

Note: raw strings are handy for file paths and regex patterns, but they cannot end with a single backslash.

Raw strings (r prefix)

A raw string tells Python to treat backslashes as regular characters instead of escape prefixes. Prefix a literal with r to create a raw string. This is often the easiest way to include python escape characters literally, for example when showing Windows paths or regular expressions.

print(r"Sammy says, \"The balloon's color is red.\"")
print(r"C:\new_folder\test.txt")

Compare raw strings to normal strings when you need to preserve the exact characters: raw strings keep backslashes intact, while normal strings interpret sequences like \n as newline.

Common tasks and quick answers

  • How to format text in python 3: combine quotes, escape sequences, triple quotes, and raw strings depending on the goal.
  • How to include quotes in a string in python: use the opposite quote type or escape with backslash.
  • Python print newline tab in string: use \n and \t inside the literal.
  • Difference between raw string and normal string in python: raw strings Netalith not process escape sequences.
  • How to print a backslash in python string: escape it as \\.

Best practices

When formatting strings, prefer readability: use triple quotes for long text blocks, raw strings for literal backslashes, and escape sequences for concise inline control.

Also consider higher-level formatting options (f-strings and format()) when you need to insert variables into strings while keeping output readable and safe.

Further reading

  • How to format text in python 3 with f-strings and str.format().
  • Python triple quotes string example for multiline literals.
  • Python raw string r prefix example and when to use it.

Summary

Mastering python string formatting involves understanding string literals vs values, using quotes intelligently, applying escape sequences for control characters like \n and \t, leveraging triple quotes for multiline text, and choosing raw strings when you need backslashes preserved. These techniques will make your python strings clear, correct, and easy to maintain.

Stay updated with Netalith

Get coding resources, product updates, and special offers directly in your inbox.