String Formatting Techniques
On this page
ConcatenationThe.format() MethodF-Strings — Modern and ReadableMini Project — Bill SplitterWhen programs display text mixed with numbers or variables, it is important to keep the output clean and readable. String formatting provides advanced ways to build such messages as it goes beyond simple concatenation and allows values to be inserted neatly inside sentences.
Python offers several approaches to do this, from the older .format() method to the modern and elegant f-strings.
Concatenation
Concatenation joins pieces of text together using the + operator. It is the simplest form of formatting, but it only works with strings — so numbers must be converted first using str().
name = "Alice"
age = 25
print("Hello, my name is " + name + " and I am " + str(age) + " years old.")Output
Hello, my name is Alice and I am 25 years old.
While this works for short messages, longer sentences can become difficult to read and maintain.
The .format() Method
The .format() method provides a cleaner way to insert values into placeholders {} within a string. This avoids explicit conversions and keeps the message easier to manage.
name = "Bob"
city = "Paris"
print("Hello, {}! Welcome to {}.".format(name, city))Output
Hello, Bob! Welcome to Paris.
Placeholders can also be ordered or named for greater clarity:
print("{1} is older than {0}".format("Alice", "Bob"))
print("Name: {n}, Age: {a}".format(n="Charlie", a=30))Output
Bob is older than Alice
Name: Charlie, Age: 30
The .format() method is flexible and remains useful in many projects, though newer Python versions favor f-strings for simplicity.
F-Strings — Modern and Readable
F-strings, introduced in Python 3.6, let you place expressions directly inside text. By prefixing a string with f, you can directly include variables or even expressions inside {}.
name = "Diana"
height = 1.70
weight = 60
bmi = weight / (height ** 2)
print(f"{name}'s BMI is {bmi:.2f}")Output
Diana's BMI is 20.76
The {bmi:.2f} syntax formats the number to two decimal places.
You can also perform calculations or call functions inside an f-string:
print(f"In five years, {name} will be {25 + 5} years old.")Use an f-string when the values are available where the message is written; .format() remains useful for templates stored separately.
Mini Project — Bill Splitter
This final project of the Basic Concepts module combines several ideas learned so far: input, type conversion, arithmetic, and f-string formatting.
Write a program that helps a group of friends split a restaurant bill evenly.
The program should: - Ask for the total bill amount. - Ask for the number of people. - Require a number of people greater than zero, then calculate how much each person should pay. - Display the result neatly formatted to two decimal places using an f-string.
Example Run:
Enter the total bill: 120
Enter the number of people: 4
Each person should pay: 30.00