Chapter 2: Formatting Output with the print Function

You can perform various output formatting features by using the print function.
For example, you can insert a single blank line by using the print function with no arguments, like this:

  • print()

The screen in below figure shows a short Python script that inserts a blank line between two other lines of output.


Another way to format output using the print function is via triple quotes.
Triple quotes are simply three sets of double quotes (""").

Below example shows how to use triple quotes to embed a linefeed character (via pressing the Enter key). When the output is displayed, each embedded linefeed character causes the next sentence to appear on the next line. Thus, the linefeed moves your output to the next new line. Notice that you cannot see the linefeed character embedded on each code line—you can see only its effect in the output.

Using Triple Quotes:

**print("""This is line one.**

**... This is line two.**

**... This is line three.""")**

This is line one.

This is line two.

This is line three.


By using triple quotes, you also can protect single and double quotes that need to be displayed in the output.

Below shows triple quotes in action to protect both single and double quotes in the same character string-

Using Triple Quotes to Protect Single and Double Quotes:

print("""He said, "I didn't know about triple quotes!" and laughed.""")

he said, "I didn't know about triple quotes!" and laughed.

Controlling Output with Escape Sequences:

An escape sequence is a character or series of characters that allow a Python statement to escape from normal behavior. The new behavior can be the addition of special formatting for the output or the protection of characters typically used in syntax. Escape sequences all begin with the backslash (\) character.

An example of using an escape sequence to add special formatting for output is the \n escape sequence. The \n escape sequence forces any characters listed after it onto the displayed output’s next line. This escape sequence is called a newline, and the formatting character it inserts is a linefeed. Below example shows an example of using \n to insert a linefeed. Notice that it causes the output to be formatted exactly as it was in above using triple quotes.

Using an Escape Sequence to Add a Linefeed:

print("This is line one.\\nThis is line two.\\nThis is line three.")

This is line one.

This is line two.

This is line three.


Using an Escape Sequence to Protect Quotes:

print('Use backslash, so the single quote isn\\'t noticed.')

Use backslash, so the single quote isn't noticed.

A Few Python Escape Sequences:


Using a Unicode Escape Sequence

print("I love my python \\u03c0!")

I love my python π!



Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?