1) c. Formatting output

Escape characters:

Suppose you were printing a bunch of items, say your shopping list. And you wanted to separate them with tab spaces or newline characters. How would you print that?

This is where escape characters come in. Many programming languages support the usage of escape characters.

These are special characters that you can put inside the print statements and they don’t literally get actually printed on the screen. Instead, they impart special meanings while printing. It is important to note that escape characters always start with a backslash.

Here are few of the most commonly used escape characters in Python:

Escape Character What gets printed
\n New line
\r Carriage Return
\t Tab space
\v Vertical Tab
\b Backspace
\s Space
\’ Prints a single quote (‘)
\” Prints a double quote (“)
\\ Prints a backslash ()

Here is an example showing escape characters. Try substituting the escape characters by picking them from the above table and see what happens:

Noah    William     Oliver  James   Benjamin    Elijah

Print command outputs:

Additionally, you can use optional keyword arguments of the print function to format the output. It is important to note that these arguments should be specified by their name when calling the function.

The print command contains the following three optional arguments:

  • “sep” – allows us to define a separator between multiple items passed to the function and defaults to a single space.
  • “end” – defines what string is added to the end of the output and defaults to a newline.
  • “file” – defines where the output should be directed and defaults to “standard output” (which is usually a terminal console). You can direct the output to other streams such as files.

Try running the following code:

1-2-3 4+5+6.

A note to visitors:

Did you notice the image on this page? Whenever you come across a concept that beginners might find difficult to visualize, you’ll find a conceptual image along with it.

Why do you need these images? These images make it easier for you to grasp the concept by helping you visualize it. This saves you a lot of time and energy in figuring it out.

Just gazing at the image and letting your mind stroll freely over it engages your mind and gives you a simple, a more direct way to own the concept.

There are lots of conceptual images later in the course. Learn actively by engaging your mind in multiple ways!

Have questions about this course? Click the red “Contact Us” button at the top or send your queries to [email protected] .