PythonString Formatting
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 theformat()
method.
F-Strings
F-string allows you to format selected parts of a string.
To specify a string as an f-string, simply put anf
in front of the string literal, like this:
Placeholders and Modifiers
To format values in an f-string, add placeholders{}
, 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 also 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)
You can also format a value directly without keeping it in a variable:
Example
Display the value95
with 2 decimals:
print(txt)
Perform Operations in F-Strings
You can perform Python operations inside the placeholders.
You can do math operations:
Example
Perform a math operation in the placeholder, and return the result:
print(txt)
You can perform math operations on variables:
Example
Add taxes before displaying the price:
tax = 0.25
txt = f"The price is {price + (price * tax)} dollars"
print(txt)
You can performif...else
statements inside the placeholders:
Example
Return "Expensive" if the price is over 50, otherwise return "Cheap":
txt = f"It is very {'Expensive' if price>50 else 'Cheap'}"
print(txt)
Execute Functions in F-Strings
You can execute functions inside the placeholder:
Example
Use the string methodupper()
to convert a value into upper case letters:
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:
Example
Create a function that converts feet into meters:
return x * 0.3048
txt = f"The plane is flying at a {myconverter(30000)} meter altitude"
print(txt)
More Modifiers
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:
Example
Use a comma as a thousand separator:
txt = f"The price is {price:,} dollars"
print(txt)
Here is a list of all the formatting types.
Formatting Types | ||
---|---|---|
:< | Try it | Left aligns the result (within the available space) |
:> | Try it | Right aligns the result (within the available space) |
:^ | Try it | Center aligns the result (within the available space) |
:= | Try it | Places the sign to the left most position |
:+ | Try it | Use a plus sign to indicate if the result is positive or negative |
:- | Try it | Use a minus sign for negative values only |
: | Try it | Use a space to insert an extra space before positive numbers (and a minus sign before negative numbers) |
:, | Try it | Use a comma as a thousand separator |
:_ | Try it | Use a underscore as a thousand separator |
:b | Try it | Binary format |
:c | Converts the value into the corresponding Unicode character | |
:d | Try it | Decimal format |
:e | Try it | Scientific format, with a lower case e |
:E | Try it | Scientific format, with an upper case E |
:f | Try it | Fix point number format |
:F | Try it | Fix point number format, in uppercase format (showinf andnan asINF andNAN ) |
:g | General format | |
:G | General format (using a upper case E for scientific notations) | |
:o | Try it | Octal format |
:x | Try it | Hex format, lower case |
:X | Try it | Hex format, upper case |
:n | Number format | |
:% | Try it | Percentage format |
String format()
Before Python 3.6 we used theformat()
method to format strings.
Theformat()
method can still be used,but f-strings are faster and the preferred way to format strings.
The next examples in this page demonstrates how to format strings with theformat()
method.
Theformat()
method also uses curly brackets as placeholders{}
, but the syntax is slightly different:
Example
Add a placeholder where you want to display the price:
txt = "The price is {} dollars"
print(txt.format(price))
You can add parameters inside the curly brackets to specify how to convert the value:
Example
Format the price to be displayed as a number with two decimals:
Check out all formatting types in ourString format() Reference.
Multiple Values
If you want to use more values, just add more values to the format() method:
And add more placeholders:
Example
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))
Index Numbers
You can use index numbers (a number inside the curly brackets{0}
) to be sure the values are placed in the correct placeholders:
Example
itemno = 567
price = 49
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
print(myorder.format(quantity, itemno, price))
Also, if you want to refer to the same value more than once, use the index number:
Example
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))
Named Indexes
You can also use named indexes by entering a name inside the curly brackets{carname}
, but then you must use names when you pass the parameter valuestxt.format(carname = "Ford")
:
Example
print(myorder.format(carname = "Ford", model = "Mustang"))