Skip to content

3.3 Print with formatted output

3.3a Print with new line character

The newline character in Python is a special character that helps us to format the output statements and it is represented as \n.

Example 3.3.1 - This example uses \n to print the data to the new line.

print("This is the first line \n and this is the second line.")

Example 3.3.1 - Output

This is the first line 
and this is the second line.

 


 

3.3b Print with end parameter

To print without a newline in Python 3, you can use the end parameter of the print() function.

This is an optional parameter in order to specify what to print at the end of each line. By default if we do not pass the end parameter, it is \n, which is a new line as we saw in 3.3.1. As we can see in Example 3.3.2, we are passing a blank space ' ' to the end parameter and that is the reason why the second line is next to the first line with just an extra space.

Example 3.3.2 - This example uses end parameter.

print("First string.", end=' ')
print("Second string.")

Example 3.3.2 - Output

First string. Second string.

 


 

3.3c Print with sep parameter

The print function also has a sep parameter that specifies the separator between the arguments. The default separator is a space ' '.

Example 3.3.3 - This example uses sep parameter.

print("Hello", "world", sep="-")

Example 3.3.3 - Output

Hello-world

 


 

Exercise 3.3.1 - Write a program to output your name and surname on two separate lines. You can use the new line character approach as explained in 3.3a or the end parameter as explained in 3.3b to achieve your results.

Exercise 3.3.1 - Model Answer - Make sure to work out the exercise before checking the model answer.