Skip to main content

5.0 Python: Format Strings

5.1 String Format

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

5.1.1 Example

Wrong
age = 36
#This will produce an error:
txt = "My name is John, I am " + age
print(txt)

But we can combine strings and numbers by using f-strings or the format() method!


5.2 F-Strings

F-String was introduced in Python 3.6, and is now the preferred way of formatting strings.

To specify a string as an f-string, simply put an f in front of the string literal, and add curly brackets {} as placeholders for variables and other operations.

5.2.1 Example

Create an f-string:

age = 36
txt = f"My name is John, I am {age}"
print(txt)

5.2.2 Example

txt = f"The price is 49 dollars"
print(txt)

5.3 Placeholders and Modifiers

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

5.3.1 Example

Add a placeholder for the price variable:

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

A placeholder can include a modifier to format the value.

A modifier is included by adding a colon : followed by a legal formatting type, like .2f which means fixed point number with 2 decimals:

5.3.2 Example

Display the price with 2 decimals:

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

A placeholder can contain Python code, like math operations:

5.3.3 Example

txt = f"The price is {20 * 59} dollars"
print(txt)

5.3.4 Example

Add taxes before displaying the price:

price = 59
tax = 0.25
txt = f"The price is {price + (price * tax)} dollars"
print(txt)

5.3.5 Example

You can perform if...else statements inside the placeholders:

price = 49
txt = f"It is very {'Expensive' if price>50 else 'Cheap'}"

print(txt)

5.4 Execute Functions in F-Strings

You can execute functions inside the placeholder:

5.4.1 Example

Use the string method upper() to convert a value into upper case letters:

fruit = "apples"
txt = f"I love {fruit.upper()}"
print(txt)

The function does not have to be a built-in Python method, you can create your own functions and use them:

5.4.2 Example

Create a function that converts feet into meters:

def myconverter(x):
return x * 0.3048

txt = f"The plane is flying at a {myconverter(30000)} meter altitude"
print(txt)