Python f-strings make it easy to insert values into text and control how those values are displayed.
An f-string begins with the letter f immediately before the quotation mark:
name = "Alex"
print(f"Hello, {name}!")
Output:
Hello, Alex!
Anything inside { } is evaluated by Python and inserted into the string.
1. Putting Variables Inside Strings
Instead of joining strings together manually, place variables inside braces.
name = "Maria"
age = 19
print(f"{name} is {age} years old.")
Output:
Maria is 19 years old.
This is usually easier to read than string concatenation.
Instead of:
print(name + " is " + str(age) + " years old.")
you can write:
print(f"{name} is {age} years old.")
2. Expressions Inside f-Strings
The contents of { } do not have to be simple variables. Python can evaluate expressions there.
x = 8
y = 5
print(f"{x} + {y} = {x + y}")
Output:
8 + 5 = 13
Another example:
price = 12.50
quantity = 4
print(f"Total: ${price * quantity}")
Output:
Total: $50.0
3. Formatting Decimal Numbers
A very common use of f-strings is controlling the number of digits displayed after the decimal point.
Use:
:.2f
to display two digits after the decimal point.
price = 7.5
print(f"Price: ${price:.2f}")
Output:
Price: $7.50
The general pattern is:
{value:.nf}
where n is the number of digits you want after the decimal point.
For example:
number = 3.1415926
print(f"{number:.1f}")
print(f"{number:.2f}")
print(f"{number:.4f}")
Output:
3.1 3.14 3.1416
Notice that Python rounds the displayed value.
4. Percentages
The % formatting option converts a decimal value into a percentage.
score = 0.8734
print(f"Score: {score:.1%}")
Output:
Score: 87.3%
Here:
.1%
means to display one digit after the decimal point.
5. Adding Commas to Large Numbers
Use a comma in the format specification to make large numbers easier to read.
population = 1234567
print(f"Population: {population:,}")
Output:
Population: 1,234,567
You can combine commas with decimal formatting:
amount = 1234567.891
print(f"${amount:,.2f}")
Output:
$1,234,567.89
6. Aligning Text
f-strings can align values within a fixed amount of space.
Suppose we want each value to take up 10 character positions.
Left aligned
name = "Python"
print(f"{name:<10}|")
Output:
Python |
The < means left align.
Right aligned
print(f"{name:>10}|")
Output:
Python|
The > means right align.
Centered
print(f"{name:^10}|")
Output:
Python |
The ^ means center.
7. Lining Up Numbers
Right alignment is particularly useful when displaying columns of numbers.
print(f"{12.5:8.2f}")
print(f"{3.75:8.2f}")
print(f"{125.9:8.2f}")
Output:
12.50
3.75
125.90
In:
{12.5:8.2f}
8means use a field that is 8 characters wide..2fmeans display 2 digits after the decimal point.
8. Creating Simple Tables
Alignment becomes especially useful when producing tables.
item1 = "Coffee"
price1 = 3.5
item2 = "Sandwich"
price2 = 8.25
print(f"{'Item':<15}{'Price':>8}")
print(f"{item1:<15}${price1:>7.2f}")
print(f"{item2:<15}${price2:>7.2f}")
Output:
Item Price Coffee $ 3.50 Sandwich $ 8.25
The text is left aligned while the numbers are right aligned.
9. Formatting Integers with Leading Zeros
Sometimes you want numbers to always have the same number of digits.
number = 7
print(f"{number:03d}")
Output:
007
Here:
0means fill unused positions with zeros.3means use three positions.dmeans format the value as an integer.
Another example:
for number in range(1, 4):
print(f"File{number:03d}.txt")
Output:
File001.txt File002.txt File003.txt
10. Useful f-String Patterns
| Goal | Format | Example Output |
|---|---|---|
| Insert a value | {x} | 17 |
| Two decimal places | {x:.2f} | 17.50 |
| One decimal place | {x:.1f} | 17.5 |
| Percentage | {x:.1%} | 87.5% |
| Add commas | {x:,} | 1,000,000 |
| Commas and decimals | {x:,.2f} | 1,000.50 |
| Left align | {x:<10} | text followed by spaces |
| Right align | {x:>10} | spaces followed by text |
| Center | {x:^10} | centered text |
| Three-digit integer | {x:03d} | 007 |
11. A Complete Example
name = "Jordan"
hours = 12.5
rate = 18.75
pay = hours * rate
print(f"Employee: {name}")
print(f"Hours: {hours:8.2f}")
print(f"Rate: ${rate:8.2f}")
print(f"Pay: ${pay:8.2f}")
Output:
Employee: Jordan Hours: 12.50 Rate: $ 18.75 Pay: $ 234.38
Key Idea
The basic f-string pattern is:
f"some text {expression}"
Formatting instructions come after a colon:
f"{expression:format}"
For example:
f"{price:.2f}"
means:
Insert the value of
priceand display it as a floating-point number with two digits after the decimal point.
For introductory Python programming, the most useful formats to remember are:
f"{value}"
f"{value:.2f}"
f"{value:>10}"
f"{value:<10}"
f"{value:8.2f}"
These cover most of the formatting needed for calculations, money, and simple tables.
