Python String Formatting

PythonBeginner
Practice Now

Introduction

Welcome to the Python String Formatting lab. Properly formatting strings is a fundamental task in any programming language, used for everything from simple print statements to generating complex reports and web pages. Python offers several ways to format strings, each with its own advantages and use cases.

In this lab, you will explore the evolution of string formatting in Python. You will start with the traditional % operator, then move to the more flexible str.format() method. You will also master f-Strings, the modern and recommended approach introduced in Python 3.6, and learn how to format numbers effectively. Finally, you'll discover Template strings, a secure option for handling templates from untrusted sources.

By the end of this lab, you will have a comprehensive understanding of how to choose and use the right string formatting technique for your Python projects.

Using the % operator

In this step, you will learn about the old-style string formatting using the % operator. This method, inherited from C's printf function, uses format specifiers like %s for strings and %d for integers to insert values into a string.

While this method works, it has some quirks and is less flexible than modern alternatives. For new code, it is strongly recommended to use f-Strings or str.format().

Note: If you are not familiar with using WebIDE (VS Code like), please learn it first at this lab.

First, open the file step1.py from the file explorer on the left.

Now, add the following code to step1.py to see how to format a string and an integer.

## % operator: old-style string formatting (not recommended for new code)
name = 'Pete'
print('Hello %s' % name)  ## %s = string placeholder

num = 5
print('I have %d apples' % num) ## %d = integer placeholder

Save the file and run it from the terminal to see the output.

python3 step1.py

You should see the following output, where %s has been replaced by the value of name and %d by the value of num.

Hello Pete
I have 5 apples

Using str.format

In this step, you'll explore the str.format() method, which was introduced in Python 3 (and back-ported to 2.7) as a more powerful and flexible way to format strings. This method uses curly braces {} as placeholders.

You can pass arguments to format() and they will be inserted into the placeholders in order. You can also use numbers inside the braces to refer to arguments by their position.

Open the file step2.py from the file explorer.

Add the following code to step2.py. The first example uses empty braces, and the second uses positional arguments.

## str.format() method: modern string formatting (Python 2.7+)
name = 'John'
age = 20

## Arguments are inserted in order
print("Hello I'm {}, my age is {}".format(name, age))

## Arguments are inserted based on position
print("Hello I'm {0}, my age is {1}".format(name, age))

Save the file and execute it in the terminal.

python3 step2.py

Both print statements will produce the same result, demonstrating the two ways to use str.format().

Hello I'm John, my age is 20
Hello I'm John, my age is 20

Formatted String Literals or f-Strings

In this step, you will master f-Strings, the recommended way to format strings in Python 3.6 and newer. An f-String is a string literal prefixed with f or F. These strings allow you to embed Python expressions directly inside them, enclosed in curly braces {}.

f-Strings are evaluated at runtime, making them not only concise and readable but also very powerful.

Open the file step3.py from the file explorer.

Basic Syntax and Expressions

First, let's look at the basic syntax and how to embed expressions. Add the following code to step3.py.

## f-string: recommended way to format strings (Python 3.6+)
name = 'Elizabeth'
print(f'Hello {name}!')  ## f prefix allows expressions in {}

## f-strings support expressions: can include calculations inside {}
a = 5
b = 10
print(f'Five plus ten is {a + b} and not {2 * (a + b)}.')

Multiline f-Strings

You can also create multiline strings by enclosing the f-String in parentheses. Add this example to step3.py.

name = 'Robert'
messages = 12
multiline_string = (
    f'Hi, {name}. '
    f'You have {messages} unread messages'
)
print(multiline_string)

The = specifier for Debugging

Starting with Python 3.8, you can use the = specifier to automatically print both an expression and its value, which is very useful for debugging. Add this final piece of code to step3.py.

## = specifier: prints both variable name and value (Python 3.8+)
from datetime import datetime
now = datetime.now().strftime("%b/%d/%Y - %H:%M:%S")
print(f'date and time: {now=}')

Now, save the file and run it from the terminal.

python3 step3.py

You will see the output from all three examples. Note that the date and time in your output will be different.

Hello Elizabeth!
Five plus ten is 15 and not 30.
Hi, Robert. You have 12 unread messages
date and time: now='...'

Formatting Digits

In this step, you will learn how to format numerical data within f-Strings. This is a powerful feature for presenting data in a human-readable format. We will cover adding thousands separators, rounding floating-point numbers, and displaying numbers as percentages.

Open the file step4.py from the file explorer.

Add the following code to step4.py to practice different number formatting techniques.

## Adding thousands separator
a = 10000000
print(f"Number with separators: {a:,}")

## Rounding a float to 2 decimal places
b = 3.1415926
print(f"Rounded number: {b:.2f}")

## Showing a number as a percentage with 2 decimal places
c = 0.816562
print(f"As a percentage: {c:.2%}")

Each format specifier follows the colon : inside the curly braces.

  • :, adds a comma as a thousands separator.
  • :.2f formats the number as a float with two decimal places.
  • :.2% multiplies the number by 100 and displays it as a percentage with two decimal places.

Save the file and run it from the terminal.

python3 step4.py

Your output should look like this:

Number with separators: 10,000,000
Rounded number: 3.14
As a percentage: 81.66%

For your reference, here is a table with more number formatting options available in f-Strings:

Number Format Output description
3.1415926 {:.2f} 3.14 Format float 2 decimal places
1000000 {:,} 1,000,000 Number format with comma separator
0.35 {:.2%} 35.00% Format percentage
1000000000 {:.2e} 1.00e+09 Exponent notation

Using Template Strings

In this step, you will learn about Template strings from Python's built-in string module. While less powerful than f-Strings, they are a safer choice when handling string templates that might be generated by users. Their reduced complexity prevents the execution of arbitrary code, which can be a security risk with methods like str.format() if not used carefully.

Template strings use dollar signs $ to mark placeholders (e.g., $name).

Open the file step5.py from the file explorer.

Add the following code to step5.py. You will need to import the Template class, create a template object, and then use the substitute() method to insert values.

from string import Template

name = 'Elizabeth'

## Create a Template object
t = Template('Hey $name!')

## Use the substitute() method to replace the placeholder
result = t.substitute(name=name)
print(result)

The substitute() method takes keyword arguments where the keys match the placeholder names in the template.

Save the file and run it from the terminal.

python3 step5.py

The output will show the substituted string.

Hey Elizabeth!

Summary

Congratulations on completing the Python String Formatting lab!

In this lab, you have explored the primary methods for formatting strings in Python. You've learned:

  • The % operator: The old C-style formatting, which is no longer recommended for new code.
  • The str.format() method: A more powerful and flexible method that uses {} placeholders.
  • f-Strings: The modern, concise, and highly recommended approach for Python 3.6+ that allows embedding expressions directly into strings.
  • Number Formatting: How to use format specifiers within f-Strings to control the presentation of numbers, including separators, precision, and percentages.
  • Template Strings: A simpler and safer mechanism for string substitution, ideal for handling templates from external or untrusted sources.

By understanding the strengths and weaknesses of each method, you can now choose the most appropriate tool for any string formatting task you encounter in your Python programming journey.