DEV Community

Cover image for The print function
Blikoor
Blikoor

Posted on

The print function

A statement is an instruction that the Python interpreter can execute. A function is a block of code that perform a specific action, and typically contain several statements. There are two types of Functions in Python: Built-in functions — pre-defined functions like print(), and User-defined functions — functions created by programmers or developers.

The print function was an addition to Python 3 and replaced the print statement of Python 2. (PEP 3105). We can print values to the screen (stdout) by default or an open file. It is, for example, commonly used in debugging. The function can accept any number of positional arguments and defines four optional keyword arguments that already have default values.

Syntax

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Parameter Description
object(s) Objects, will be converted to string before printed.
sep='separator' Optional — specify how to separate the objects, if there is more than one. The default is ' '.
end='end' Optional — specify what to print at the end. The default is '\n' character (newline).
file Optional — an object with a write method. The default is sys.stdout.
flush Optional — a Boolean, specifying if the output is flushed (True) or the default buffered (False).

Escape sequences

First, let's briefly discuss these special characters since they often appear in string literals with a preceding backslash \. They allow the representation of invisible control characters and sometimes the escaping of otherwise illegal characters.

Code Description
\' single quote
\" double quote
\\ backslash
\n, \r, \r\n newline or line feed (LF)
\r carriage return (CR)
\t tab
\b backspace

Note that a newline can be a single control character or a sequence of control characters depending on the operating system (OS).

  • Windows & Dos represent an EOL as \r\n.
  • Unix, Linux and macOS represent an EOL as \n.
  • Mac OS X represent an EOL as \r.

Printing to terminal

1. You can print a blank line (\n), passing no arguments with empty parentheses.

print()
Enter fullscreen mode Exit fullscreen mode

2. You can print literals. A literal is a notation for representing a value in source code. There are various value types (int, float, tuple, string, etc.).

print(17)
print(3.14159)
print((58, 128, 168))
print("Press \"Enter\" to continue.")
Enter fullscreen mode Exit fullscreen mode

[run code]

3. You can print variables. A variable is a symbolic name that references or points to the computer memory location used to store a value.

pi = 3.14159
message = "Press 'Enter' to continue."
print(message)
print(pi)
Enter fullscreen mode Exit fullscreen mode

[run code]

4. You can print expressions directly. An expression is combination of operators and operands that is interpreted to produce some other value.

print(19 + 23)
print("Python was first released " + str(31) + " years aggo.")
Enter fullscreen mode Exit fullscreen mode

[run code]

5. You can print multiple literals, separating them with a comma (,).

series = "Monty Python's Flying Circus"
print("Python was named after the BBC comedy series:", series)
print(29, 31, 37)
Enter fullscreen mode Exit fullscreen mode

[run code]

6. You can print values with another separator (see sep).

print('Hello', 'World!', sep="")
print("", "C", "Users", "Guido", "Documents", sep="/")
print("name", "email", "phone number", "address", sep="," )
Enter fullscreen mode Exit fullscreen mode

[run code]

7. You can print literals without line breaks or trailing newline character (see end).

print("Proceed with Format (Y/N)? ", end="")
print("Y")
Enter fullscreen mode Exit fullscreen mode

[run code]

String formatting

Since Python 3.6, you can format string literals with f-strings (PEP 498). Although this is now the recommended way to format string literals, it is not intended completely replace the str.format() and printf-style formatting mechanisms.

A formatted string literal or f-string is a string literal that is prefixed with f or F. These strings may contain replacement fields, which are expressions delimited by curly braces ({}). The format specification mini-language is the same as that used by the str.format() method.

Syntax

"{" [field_name] ["!" conversion] [":" format_spec] "}"

Arguments Description
field_name Specifies the object whose value is to be formatted and inserted.
conversion Optional — type coercion, to force a type conversion (prefixed with !).
format_spec Optional — specification of how the value should be presented (prefixed with :).

field_name

arg_name ("." attribute_name | "[" element_index "]")*

Arguments Description
arg_name [identifier digit+]
attribute_name identifier
element_index digit+ index_string

conversion

"r" | "s" | "a"

Arguments Description
r Calls repr() on the argument before format_spec implement __format()__.
s Calls str() on the argument before format_spec implement __format()__.
a Calls ascii() on the argument before format_spec implement __format()__.

format_spec

[[fill]align] [sign] [#] [0] [width] [grouping_option] [.precision] [type]

Arguments Description
fill <any character>
align < > = ^
sign + - " "
width digit+
grouping_option _ ,
precision digit+
type b c d e E f F g G n o s x X %

8. You can print expressions in f-strings.

print(f"{43 * 47}")
Enter fullscreen mode Exit fullscreen mode

[run code]

9. You can print variables in f-strings (see field name).

nation = ("Mayan")
logo = [2, (52, 121, 175), (255, 222, 77)]

print(f"The Python logo depicts {logo[0]} colored snakes based on ancient \
{nation} drawings.")
Enter fullscreen mode Exit fullscreen mode

[run code]

10. You can call methods in f-strings (see field name).

group = "Monty Python"
print(f"Eric Idle is an actor of the comedy group {group.upper()}.")
Enter fullscreen mode Exit fullscreen mode

[run code]

11. You can call functions in f-strings (see field name).

def to_upper(string):
    return string.upper()

group = "Monty Python"  
print(f"Eric Idle is an actor of the comedy group {to_upper(group)}.")
Enter fullscreen mode Exit fullscreen mode

[run code]

12. You can print objects in f-strings (see field name). By default, it will print whatever the __str__ method returns, or you can use explicit conversion flags (see conversion).

class Color:
    def __init__(self, r = 255, g = 255, b = 255):
        self.r = r
        self.g = g
        self.b = b

    def __str__(self):
        return "This is a RGB color object."

    def __repr__(self):
        return f"Color({self.r}, {self.g}, {self.b})"

flat_blue = Color(r = 52, g = 121, b = 175)
light_gold = Color(r = 255, g = 222, b = 77)

print(f"{flat_blue}")
print(f"{flat_blue!s}")
print(f"{light_gold!r}")
Enter fullscreen mode Exit fullscreen mode

[run code]

13. You can format the alignment and padding of values in f-strings (see align and fill).

prime_number = 997
language = "Python"

print(f"{prime_number}")
print(f"{97:>3}")
print(f"{prime_number:0>10}")
print(f"{language:^10}")
print(f"{language:-^10}")
Enter fullscreen mode Exit fullscreen mode

[run code]

14. You can format the sign, grouping and rounding of numbers in f-strings (see sign, grouping_option, and precision).

number = 9576890767
amount = 25169.15683

print(f"{number:,}")
print(f"{amount:=+11,.2f}")
print(f"$ {amount:,.2f}")
print(f"R {amount:,.2f}".replace(',', ' '))
Enter fullscreen mode Exit fullscreen mode

[run code]

15. You can format values as different types in f-strings (see type).

decimal_number = 29
binary_number = 0b11101
index = 0.2827
big_number = 176846309399143769411680

print(f"{decimal_number:5b}")
print(f"{decimal_number:5o}")
print(f"{decimal_number:5x}")
print(f"{decimal_number:5X}")
print(f"{binary_number:5d}")
print(f"{big_number:e}")
print(f"Python has a PYPL-index of {index:.2%}")
Enter fullscreen mode Exit fullscreen mode

[run code]

Printing to a file

The print function doesn't just send text to the screen but more accurately converts objects to strings and writes them to a stream (file-like object). A stream can be any file on your drive, a network socket, or a location in memory (buffer). In addition to this, the operating system provides three standard streams:

Stream File Handle Desciption
stdin (standard input) 0 keyboard input
stdout (standard output) 1 screen output
stderr (standard error) 2 screen output

As mentioned earlier, the print function use stdout by default. However, using a redirection operator (>), we can instruct the operating system to use a file stream instead. The redirection operator can either redirect input to a shell command or output from a shell command. To redirect stderr, you need to use a file handle. File handles are constant numbers associated with the standard streams. These handles allow you to redirect one or more streams at a time.

Syntax Descrption
program > file Redirect stdout to a file.
program 2> file Redirect stderr to a file.
program > file 2> file Redirect stdout and stderr to separate files.
program >> file Append stdout to a file.
program < file Type a text file and pass the text to program.

For example, you might execute systeminfo.exe to save the information provided by the systeminfo command to a file.

PS systeminfo > system_info.txt
Enter fullscreen mode Exit fullscreen mode

16. You can use stream redirection for various command-line programs including your own Python scripts.

# message.py
print("This message will be written to stdout")
Enter fullscreen mode Exit fullscreen mode
PS python message.py > message.txt
Enter fullscreen mode Exit fullscreen mode

17. You can use stream redirection in Python. This is done by first obtaining a reference to the standard output using the stdout file object of the sys module. Its a good practice to store the original value of the standard output in a variable before changing it. This way you can reset it back to its original value afterwards. The with statement creates a runtime context that allows you to run a group of statements under the control of a context manager. The open function tries to open a file in writing mode and if successful returns a file object also called a handle. The following modes are commonly used with the print function:

Mode Description
'r' Open for reading (default).
'w' Open for writing, truncating the file first.
'x' Open for exclusive creation, fails if the file already exists.
'a' Open for writing, appending to the end of file if it exists.
'+' Open for updating (reading and writing).
import sys


default_stdout = sys.stdout # save the original value of stdout

print("This message will be written to stdout.")

with open('message.txt', 'w') as file_object:
    sys.stdout = file_object # redirect stdout to the file
    print("This message will be written to file.")
    sys.stdout = default_stdout # reset stdout to its original value

print("This message will be written to stdout.")
Enter fullscreen mode Exit fullscreen mode

18. You can print to a file directly without using stream redirection (see file).

import sys


print("This message will be written to stdout.")

with open('message.txt', 'w') as file_object:
    print("This message will be written to file.", file=file_object)
Enter fullscreen mode Exit fullscreen mode

19. You can disable buffering of the standard output. The operating system buffers expensive I/O operations to enhance performance, but sometimes buffering can have undesired effects. There are three kinds of streams concerning buffering — unbuffered, line-buffered, and block-buffered. A line-buffered stream waits until there is a EOL in the buffer, whereas a block-buffered stream waits for the buffer to fill up. The standard output is both line-buffered and block-buffered, depending on which event comes first. (see flush)

from time import sleep


for number in reversed(range(10 + 1)):
    print(number, end=" ", flush=True)
    sleep(1)
print("Launch!")
Enter fullscreen mode Exit fullscreen mode

20. To round off our look at the print function, here is a real-world example of a text-based progress bar that can be used for command line programs.

from time import sleep


width = 10

for progress in range (101):
    fill = width * progress // 100
    track = width - fill
    value = f"{progress / 100:.0%}"
    print("\r[", "#" * fill, " " * track, "]", value, sep="", end="", flush=True)
    sleep(0.1)
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)