How do you print output in Python? All four methods are explained.
Table of Contents
Introduction
To print output in python we use a print() function.
Anything you want to display on the output screen should be passed as an argument inside the print() function. However, there are fancier ways of output formatting. It gives more control while printing an output. The four ways to print output in python are;
- Manual String Formatting
- Formatted string literals or f-strings
- The String format() Method
- Old string formatting or printf() style in C
Manual string formatting
To display objects to the output console, pass them as a comma-separated list of arguments to print() function.
Example:
lang = "Python"
print("Welcome to",lang, "Programming")
print("Printing lang three times:", lang*3)
Output:
Welcome to Python Programming
Printing lang three times: PythonPythonPython
By default, print() separates each object by a single space and appends a newline to the end of the output.
The print() function takes two optional arguments that provide control over the output we actually want, i.e. sep and end keyword; the sep keyword argument causes objects to be separated by a string passed as a value to it. The end keyword argument causes output to be terminated by a string passed as a value to it instead of the default newline.
Let’s write a program subject.py where the print() function takes these two arguments;
print("ENG", "MATH", "DZO", "GEO", sep="|", end="***")
The program will print the string passed inside the print() function separated by “|” and ended with three *.
ENG|MATH|DZO|GEO***
Normally, without these two arguments, you will see the output shown below:
>>>print("ENG", "MATH", "DZO", "GEO")
ENG MATH DZO GEO
To print the output without any spaces, we pass an empty string to the sep keyword, i.e. sep = “”;
>>> print("ENG", "MATH", "DZO", "GEO", sep=””)
ENGMATHDZOGEO
To print the output in the same line, we end the line with empty white space, i.e. end=” ”;
>>>for i in range(5):
print(i, end=" ")
0 1 2 3 4
Formatted string literals or f-strings
Formatted string literals (also called f-strings for short) let you include the value of Python expressions inside a string by prefixing the string with f or F and writing expressions as {expression}.
It works only in python version 3.6 and above.
Example:
name = "Dawa"
print(f"{name} this is an example of a formatted string")
Output:
Dawa this is an example of a formatted string
F-string supports an equal sign (=) for self-documenting expressions and debugging (new in version 3.8);
Example:
user = "Dawa"
pw = "d2020"
print(f"{user= } \n{pw=}")
Output:
user= 'Dawa'
pw='d2020'
The additional advantage of using formatted string literals is to combine (concatenate) strings and numbers.
We cannot combine numbers and strings using the + operator. For instance, the program below will give you an error;
name = "Dawa"
age = 23
print(name + " you are "+ age+ "years old")
Error message:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
print(name + " you are "+ age+ "years old")
TypeError: can only concatenate str (not "int") to str
But we can combine string and numbers using the f-string method;
name = "Dawa"
age = 23
print(f"{name} you are {age} years old")
Output:
Dawa you are 23 years old
Previous post: Input() function
The string format() method
Basic usage of the format() method looks like this; (We will use the above program but will format the output using a string format() method.)
Example:
name= "Dawa"
age = "23"
print ("{} you are {} years old".format(name, age))
Output:
Dawa you are 23 years old
We can also pass a number inside a bracket. A number in the brackets can be used to refer to the position of the object passed into the format() method.
Example:
print('{0} {2} {3} {1}'.format(5,4,3,7))
Output:
5 3 7 4
The additional feature of the format() method is to control the floating-point in the number;
Example:
PI = 3.14159265
print('The value of PI is {:.2f}'.format(PI))
Output:
The value of PI is 3.14
.2f is to print the PI value in two decimal points.
The positional and keyword arguments can be arbitrarily combined in format() method;
Example:
print("Welcome to {lang} {0}".format( "Programming", lang="Python"))
Output:
Welcome to Python Programming
Old string formatting or printf() style in C
String objects have one unique built-in operation: the % operator (modulo). This is also known as the string formatting or interpolation operator. Given format % values (where the format is a string), % conversion specifications in format are replaced with zero or more elements of values.
Example:
print('%d %s cost Nu.%.2f' % (6, 'bananas', 60))
Output:
6 bananas cost Nu.60.00
The few conversion types are:
%d – Integer
%f – float
%s – String
%x – hexadecimal
%o – Octal