0% found this document useful (0 votes)
16 views

String Formatting

The document discusses different techniques for formatting strings in Python, including string concatenation, using the .format() method, and f-strings. It provides examples of each technique, showing how to format a string to include a name and age. The exercise at the end demonstrates using f-strings to format a message about a book including its title, author, publication year, and price.

Uploaded by

Judith Nelson
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

String Formatting

The document discusses different techniques for formatting strings in Python, including string concatenation, using the .format() method, and f-strings. It provides examples of each technique, showing how to format a string to include a name and age. The exercise at the end demonstrates using f-strings to format a message about a book including its title, author, publication year, and price.

Uploaded by

Judith Nelson
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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."

2. String Formatting with .format() Method:

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)

3. f-Strings (Formatted String Literals) - Python 3.6+:

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:

Title of the book: "The Catcher in the Rye"

Author's name: "J.D. Salinger"

Publication year: 1951

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.

You might also like