Python: Outputting data to the console

by Alex
Python: Outputting data to the console

When developing programs, data output to the console is used all the time. For example, when testing the functions of a program that has not yet acquired a graphical interface, or as a means of finding errors and debugging the code. Python gives you the tools to not only print to the console, but to format it.

The print function and its parameters

The print() function is included in the standard Python library as the main tool for outputting data to a console or any other device (screen, printer and so on). The programmer can customize the output using function arguments:


This is the data that is displayed on the screen. The programmer sends as many objects as he wants to the function, which are automatically converted to string format and sent to the output stream. When passing objects to a function, the programmer can pass them by commas or use concatenation. Passing several arguments will not cause a conflict between *objects and other optional arguments, because the interpreter automatically recognizes the other parameters by the keyword (sep, end, file, flush)! Here’s an example:

print("apple", "orange" + " banana", "cherry")

apple orange banana cherry


This argument defines what to put between the passed objects. The default value of sep is ” “, that is, if we put a space between several objects, we will change it to another symbol, like “-“:

print("One", "Two", "Three", sep="-")



The argument specifies the character that print() ends with. By default it is a line break character “n”, i.e. when all data are printed the carriage moves to the next line, and the next print output starts on a new line. If you want the output of several prints to be on one line, replace the last character. Here is an example:

print("Two," end=" ")

Two Three


This argument allows you to override the output stream. By default it is set to “sys.stdout”, which means that the data are output to the console. If you specify a file instead, the data will be written to it. Here’s an example of a Python script that opens the file temp.txt and writes text to it using the print function:

with open("temp.txt", "w") as f:
    print("Write to file", file=f)


This optional argument allows you to flush the output stream. It defaults to False when the output is buffered, the programmer can specify “True” so that the output is produced immediately. For example, if you write data to a file, it goes into the buffer and is actually written to the file when the buffer fills or the file is closed. Similarly with output to the console, the data is written to the buffer and output from it to the console. If flush is set to True, the output is done immediately.

print("Some text", flush=True)

Formatted output

In order for the information printed to the console to be easily read and understood, it must be formatted. Python provides tools that allow the programmer to format the console output in different ways. You can even use them to create a smooth and readable table.

% Operator

The % operator is often used for formatting and is well known not only to Python programmers, but also to C/C++ programmers. In essence, the % operator is a label, instead of which a variable value or expression is substituted. The % operator is placed directly in the output string, and the substituted values are placed in the tuple after the second %. Example:

print("Program number %2d, got result: %5.2f" % (4, 7.3333))

Program number 4, result: 7.33

In addition to the % character, the type of value is specified, as well as, optionally, length and precision. The syntax looks like this:


If you examine the example, you can see that:

  • %2d” is used for the first element of the tuple, the integer “4”. Since % is followed by a length of “2” and the number in the tuple is only one digit, an extra space will be added to the output.
  • %5.2f” is the format for floating point numbers. “5” is the total number of digits the string should contain, and “.2” is the number of digits after the decimal point.

Format method

This tool was added in Python version 2.6. Compared to the previous method format turns out to be a bit more cumbersome. The programmer uses the “{}” symbol to mark the place where the variable or expression will be substituted. Inside the curly braces you can specify the name, value type, width, and precision. The values to be substituted are specified in the tuple after the format keyword. They can be specified either positively or assigned by name. Example:

print('{0} {1} January celebrates {other} birthday'
    .format('Nikita', '25', other ='15th'))

Nikita is celebrating his 15th birthday on January 25th

The format method also allows you to format numbers, that is, specify their width and precision:

print("Robot #{r:4d} weighs {w:6.2f}"
    .format(r = 1134, w = 112.5534))

Robot #1134 weighs 112.55

This method allows very flexible formatting of the data output. For example, the programmer can pass data from a ready-made dictionary into the string:

data = dict(name ="Bender", race ="Robot")
print("This is {name}, he is {race}".format(**data))

This is Bender, he's a Robot

String method

String method output is generated using slice operations and string methods. Several methods have been created to work with string data type that allow you to simply and elegantly format the output, among them methods: ljust(), rjust(), center().


This function centers a string according to a specified width, filling in the missing width with whitespace. It has the following syntax:, fillchr)


  • str is the string that we are going to center.
  • len is the width of the string.
  • fillchr is the character to fill the missing space (by default it is space).


text = "This text is centered."

          This text is centered
It’s important to realize that this function does not center text in the console, but in the center of a given width field (50 characters in this example).

If you change the fill character, you get the following:

text = "This text is placed in the center."
print(, "_"))

__________This text is in the center__________


The method works similarly to centre(), only it aligns text to the left side, not to the center. That is, missing characters are added not on both sides, but only on the right.


This method works similarly to centre(), but aligns the text to the right. That is, characters are added only from the left side.


Sometimes you just need to insert the value of a variable in some part of the string. You can use one of the formatting methods, build long constructions from combinations of strings and variable names connected by commas (or “+”), for example:

print("I", age, ", now I can go to", place, "whenever I want")

However, in Python version 3.6, a simple and convenient tool called the f-string or interpolated string was added to the language. You can use it to conveniently insert variables anywhere in the output string. For this purpose, curly braces “{}” are used, inside which the name of the variable is specified, and the “f” symbol is placed before the string. Example:

name = "Bob"
age = 25
print(f "{name} is celebrating his {age} birthday today")

Bob is celebrating his 25th birthday today

Fields of a given width

The above examples have already used tools to customize the width of the fields. The width of the output field is adjusted by inserting a numeric value between the “%” sign and the output type (for example, “d”). In other words, setting the width of the field looks like this:

print("%6d %6d" % (6, 6))

     6 6

Setting the width of the fields works like this:

  • The interpreter gets information about the numeric value of the output width (in the example it is “6”).
  • Then it gets information about the value to be substituted, that is, it counts how many characters it consists of (in the example it is “1”).
  • If the number of characters in the substituted value is less than the line width, extra spaces are added to the line, otherwise the value is simply output.
Fields of a given width are vital to displaying tables or two-dimensional arrays in the console. Because of the different lengths of the elements, the columns warp, resulting in a loss of readability, but if you use fields of a given width, as long as the lengths of the values are less than the width of the field, they will all be placed strictly under each other.


With formatted output you can completely customize any output to the console, for example:

Error output

Below is an example of error handling. We catch an exception in the except block and print it out using the print function.

    for i in range(4):
        if (i == 3):
            i = text
        print(f "Attempt {i} succeeded")
except Exception as err:
    print("An error has occurred: "{}"".format(err))

Attempt 0 was successful
Attempt 1 was successful
Attempt 2 was successful
An error occurred: "name 'text' is not defined"

List output

Below is an example of how to output a one line list:

a = ['python', 3, 'best', 'language', 'programming']
for val in a:
    print(val, end=' ')

python 3 best programming language

If you want to list the elements of a list in a column with ordinal numbers, you can do it as follows:

mylist = ['cat', 'dog', 'mole', 'hedgehog']
for i, x in enumerate(mylist):
    print("{a:d} : {b:6s}".format(a = i + 1, b = x))

1 : cat   
2 : dog
3 : mole
4 : hedgehog

Array output

Here we print the array line by line, specifying the element numbers.

from array import *
arr = array('i', [1,3,6,2,5])
for i in range(len(arr)):
    print("%d-th element of the array = %d" %(i, arr[i]))

0-th element of the array = 1
1st array element = 3
2nd array element = 6
3rd array element = 2
4th array element = 5

Dictionary output

Here are two options for dictionaries. Simple variant:

a = {1: "one", 2: "two", 3: "three"}
for key, value in a.items():
  print("{0}: {1}".format(key,value))

1: one
2: two
3: three

As atable:

arr = {"one": "one", "two": "two", "three": "three"}
print(" _________________ ")
print("| Rus : Eng |")
for key, value in arr.items():
    print("| {r:5s} : {w:5s} |".format(r = key, w = value))

| Rus : Eng |
| one |
| two |
| three |

Matrix output

The problem with the matrix output is that due to different lengths of numbers, the column elements will not stand under each other, but with an offset. You can solve this problem with formatting.

mtx = [[ 2, 4, 12],
       [ -6, 3, 9],
       [334, 0, 11]]
for row in mtx:
    for x in row:
        print("%3d" %(x), end = " ")

  2 4 12 
 -6 3 9
334 0 11

Here we have created a matrix in the form of two-dimensional lists, but if you work with matrices using the NumPy library, the output to the console is formatted there automatically.

Related Posts