Basic Usage

The print() function in Python is used to output text or other data to the console or standard output. It can print strings, numbers, variables, and more, and supports multiple arguments and formatting.

print("Hello, world!")
# Output: Hello, world!

Multiple Arguments

You can pass multiple arguments to the print() function. The arguments are separated by commas.

print("The answer is", 42)
# Output: The answer is 42

Separator and End Parameters

The print() function in Python has two optional parameters, sep and end, that can be used to customize the output of the function.

print("apple", "banana", "cherry", sep=", ")
# Output: apple, banana, cherry

print("Hello", end=" ")
print("world!")
# Output: Hello world!

Printing Variables

name = "Alice"
age = 30
print("Name:", name)
print("Age:", age)
# Output: 
# Name: Alice
# Age: 30

Formatted String Literals (f-strings)

Python 3.6 introduced f-strings, which provide a concise and convenient way to embed expressions inside string literals, using curly braces {}. They are prefixed with the letter f or F and are evaluated at runtime.

name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alice and I am 30 years old.

Using str.format()

str.format() is a built-in method that allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional formatting.

name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
# Output: My name is Alice and I am 30 years old.

Using %-formatting

This is an older method of formatting strings in Python. It uses the % operator to format a set of variables enclosed in a tuple (fixed-size array). The format string contains one or more format codes, which specify how the values should be formatted.

name = "Alice"
age = 30
print("My name is %s and I am %d years old." % (name, age))
# Output: My name is Alice and I am 30 years old.

Printing a List

fruits = ["apple", "banana", "cherry"]
print(fruits)
# Output: ['apple', 'banana', 'cherry']

File Parameter

The file parameter in the print() function is used to specify the file to write the output to. By default, the output is printed to the console.

# Redirecting print output to a file
with open("output.txt", "w") as file:
    print("Hello, world!", file=file)
# This writes "Hello, world!" to the file "output.txt"

Flush Parameter

The flush parameter in the print() function is used to forcibly flush the stream. By default, the stream is not flushed.

import time

for i in range(5):
    print(i, end=" ", flush=True)
    time.sleep(1)
# Output: 0 1 2 3 4 (printed with a delay of 1 second between each number)