Loading lesson path
Concept visual
Start at both ends
Formula
F - String was introduced in Python 3.6, and is now the preferred way of formatting strings.Before Python 3.6 we had to use the format() method.
Formula
F - string allows you to format selected parts of a string.
To specify a string as an f - string, simply put an fin front of the string literal, like this:
Formula
txt = f"The price is 49 dollars"print(txt)Formula
To format values in an f - string, add placeholders{}, a placeholder can contain variables, operations, functions, and modifiers to format the value.Add a placeholder for the price variable:
price = 59 txt = f"The price is {price} dollars"
print(txt)A placeholder can also 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:
Display the price with 2 decimals:
price = 59 txt = f"The price is {price:.2f} dollars"
print(txt)You can also format a value directly without keeping it in a variable:
95 with 2 decimals:
txt = f"The price is {95:.2f} dollars"
print(txt)You can perform Python operations inside the placeholders.
Perform a math operation in the placeholder, and return the result:
txt = f"The price is {20 * 59} dollars"
print(txt)You can perform math operations on variables:
Add taxes before displaying the price:
price = 59 tax = 0.25 txt = f"The price is {price + (price * tax)} dollars"
print(txt)You can perform if...else statements inside the placeholders:
Return "Expensive" if the price is over 50, otherwise return "Cheap":
price = 49 txt = f"It is very {'Expensive' if price>50 else 'Cheap'}"
print(txt)You can execute functions inside the placeholder:
to convert a value into upper case letters: fruit = "apples"
txt = f"I love {fruit.upper()}"
print(txt)Formula
The function does not have to be a built - in Python method, you can create your own functions and use them: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)At the beginning of this chapter we explained how to use the.2f modifier to format a number into a fixed point number with 2 decimals. There are several other modifiers that can be used to format values:
Use a comma as a thousand separator:
price = 59000 txt = f"The price is {price:,} dollars"
print(txt)Here is a list of all the formatting types.
:<
Left aligns the result (within the available space) :>
Right aligns the result (within the available space) :^
Center aligns the result (within the available space) :=