String Formatting
String Formatting
In Python, you can format strings using different techniques. Properly formatted strings are essential
for displaying information clearly and efficiently in your programs. There are several ways to format
strings in Python, including:
1. String Concatenation:
String concatenation involves combining strings using the + operator. This method is simple but can
become cumbersome when dealing with multiple variables and complex formatting.
name = "John"
age = 30
message = "My name is " + name + " and I am " + str(age) + " years old."
The .format() method is a more versatile way to format strings. You can use placeholders within the
string and specify values to replace them using the .format() method.
name = "John"
age = 30
message = "My name is {} and I am {} years old.".format(name, age)
f-Strings are the most modern and convenient way to format strings. They allow you to embed
expressions inside string literals, making string formatting more readable and concise.
name = "John"
age = 30
message = f"My name is {name} and I am {age} years old."
Exercise: String Formatting
Instructions:
Write a Python program that formats a message about a book using the following details:
Price: £19.99
Use f-Strings (Formatted String Literals) to create a message in the following format:
In this modified version, the exercise and solution both use f-Strings exclusively for string formatting,
without any reference to the % operator.