Python -Format - Strings
String Format
As we learned in the Python Variables chapter, we cannot combine strings and numbers like this:
But we can combine strings and numbers by usingf-strings or theformat()
method!
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 anf
in front of the string literal, and add curly brackets{}
as placeholders for variables and other operations.
Placeholders and Modifiers
A placeholder can contain variables,operations, functions, and modifiers to format the value.
Example
Add a placeholder for theprice
variable:
txt = f"The price is {price} dollars"
print(txt)
A placeholder can include amodifierto 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:
Example
Display the price with 2 decimals:
txt = f"The price is {price:.2f} dollars"
print(txt)
A placeholder can contain Python code, like math operations:
Example
Perform a math operation in the placeholder, and return the result:
print(txt)
Learn more about String Formatting in ourString Formatting chapter.