Python String Formatting

Learn how to properly format strings in Python, especially when combining strings with numbers. Discover the issue with directly concatenating strings and numbers and see an example that demonstrates a syntax error.



String Formatting

As we learned in the Python Variables chapter, we cannot directly combine strings and numbers like this:

Example

Example (with Syntax Error)

age = 25
txt = "My name is Alice, I am " + age
print(txt)  # This will cause an error
Error Output

Traceback (most recent call last):
  File "demo_string_format_error.py", line 2, in 
    txt = "My name is John, I am " + age
TypeError: must be str, not int

To combine strings and numbers, we can use f-strings or the format() method.

F-Strings

F-Strings, introduced in Python 3.6, are now the preferred way of formatting strings. To create an f-string, simply prefix the string with an f and use curly brackets {} as placeholders for variables and expressions.

Example

Create an f-string:


age = 25
txt = f"My name is Alice, I am {age}"
print(txt)
      
Output

My name is Alice, I am 25
      

Placeholders and Modifiers

Placeholders can contain variables, operations, functions, and modifiers to format the value.

Example

Add a placeholder for the price variable:


price = 79
txt = f"The price is {price} dollars"
print(txt)
Output

The price is 79 dollars

A placeholder can include a modifier to format the value. For example, .2f means a fixed point number with 2 decimal places.

Example

Display the price with 2 decimals:


price = 79
txt = f"The price is {price:.2f} dollars"
print(txt)
Output

The price is 79.00 dollars

Placeholders can also contain Python code, such as mathematical operations.

Example

Perform a math operation in the placeholder and return the result:


txt = f"The total cost is {20 * 79} dollars"
print(txt)
Output

The total cost is 1580 dollars