Formatting Python Print Statements

PythonPythonBeginner
Practice Now

Introduction

The print() function is a built-in function in Python that allows you to display output to the console. It is a useful tool for debugging and for presenting information to the user. In this lab, we will explore the different ways you can use the print() function to format your output.

Achievements

  • print()
  • Format Specifiers
  • f-Strings

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-91{{"`Formatting Python Print Statements`"}} python/with_statement -.-> lab-91{{"`Formatting Python Print Statements`"}} python/variables_data_types -.-> lab-91{{"`Formatting Python Print Statements`"}} python/numeric_types -.-> lab-91{{"`Formatting Python Print Statements`"}} python/tuples -.-> lab-91{{"`Formatting Python Print Statements`"}} python/dictionaries -.-> lab-91{{"`Formatting Python Print Statements`"}} python/standard_libraries -.-> lab-91{{"`Formatting Python Print Statements`"}} python/build_in_functions -.-> lab-91{{"`Formatting Python Print Statements`"}} end

Print() Function

The most basic use of the print() function is to simply pass it a string, and it will print that string to the console.

Open up a new Python interpreter session and type the following code:

python3
print("Hello, World!")

This will output the string "Hello, World!" to the console.

You can also pass multiple arguments to the print() function, and it will print them separated by a space by default. For example:

print("Hello,", "World!")

This will output the string "Hello, World!" to the console.

Format Specifiers

You can use format specifiers to control how values are printed. Format specifiers start with a % character, followed by a letter that specifies the type of value being printed (e.g. s for string, d for integer). For example:

name = "Alice"
age = 30
print("%s is %d years old." % (name, age))

This will output the string "Alice is 30 years old." to the console.

Here are some common format specifiers:

  • %s: string
  • %d: integer
  • %f: float
  • %x: hexadecimal

Here are some examples of using format specifiers:

## print a string
print("Hello, %s!" % "World")

## print an integer
print("The answer is %d." % 42)

## print a float
print("The value of pi is approximately %f." % 3.14159)

## print a hexadecimal value
print("The hexadecimal value of 255 is %x." % 255)

You can also specify a width and precision for the value being printed. For example:

## print a float with a width of 10 and a precision of 2
print("The value of pi is approximately %10.2f." % 3.14159)

This will output the string "The value of pi is approximately 3.14." to the console, with the float value right-aligned in a field of width 10 and a precision of 2.

F-Strings

f-strings (short for formatted strings) are a more recent addition to Python and provide a concise and convenient way to embed expressions inside string literals, using {} placeholders. They were introduced in Python 3.6 and are now the recommended way to format strings in Python.

Here's an example of using an f-string to print a string and a variable:

name = "Alice"
print(f"Hello, {name}!")

This will output the string "Hello, Alice!" to the console.

You can also use expressions inside f-strings:

x = 10
y = 20
print(f"{x} + {y} = {x + y}")

This will output the string "10 + 20 = 30" to the console.

f-strings also support format specifiers, similar to the % operator. For example:

x = 3.14159
print(f"The value of pi is approximately {x:.2f}.")

This will output the string "The value of pi is approximately 3.14." to the console.

f-strings are generally easier to read and write than the % operator, and they are also more efficient at runtime. However, they are not available in older versions of Python, so if you need to support those versions, you will need to use the % operator or another method for formatting strings.

Summary

In this lab, we learned how to use the print() function to display output to the console, and how to format that output using the f-strings, and format specifiers.

Other Python Tutorials you may like