String formatting in Python refers to the process of creating strings by incorporating variables or values within them. There are several ways to format strings in Python, and I’ll cover a few of them.
name = "Omar" age = 20 message = "My name is " + name + " and I am " + str(age) + " years old." print(message)
name = “Omar”
age = 20
message = “My name is %s and I am %d years old.” % (name, age)
print(message)
name = "Omar" age = 20 message = "My name is {} and I am {} years old.".format(name, age) print(message)
name = "Omar" age = 20 message = f"My name is {name} and I am {age} years old." print(message)
name = “Omar”
age = 20
message = “My name is {0} and I am {1} years old. I like {2}.”.format(name, age, “Python”)
print(message)
from string import Template name = "Omar" age = 20 template = Template("My name is $name and I am $age years old.") message = template.substitute(name=name, age=age) print(message)
Each method has its advantages and use cases, but f-strings (formatted string literals) introduced in Python 3.6 are often considered more readable and convenient.
Choose the method that best fits your needs and the version of Python you are working with.
Concatenation:code example
Concatenation is the process of combining two or more strings into a single string.
In Python, you can use the + operator for string concatenation.
Here’s an example with explanation:
# Example: first_name = "Omar" last_name = "AboBakr" # Concatenating first name and last name full_name = first_name + " " + last_name # Displaying the result print("Full Name:", full_name)
Explanation:
Variable Assignment:
first_name is assigned the string value “Omar”.
last_name is assigned the string value “AboBakr”.
Concatenation:
The + operator is used to concatenate the strings stored in first_name, a space (” “), and the strings stored in last_name.
The result is a new string formed by joining the first name, a space, and the last name.
Variable Assignment (cont.):
The concatenated string is assigned to the variable full_name.
Print Statement:
The print statement is used to display the result.
The output will be: Full Name: Omar AboBakr
The % operator is used for string formatting and is often referred to as “percent” or “modulo” formatting.
It allows you to embed values into a string by using placeholders that are replaced by the values specified in a tuple.
Here’s an example with an explanation:
# Example: name = "Omar" age = 20 # %-Formatting message = "My name is %s and I am %d years old." % (name, age) # Displaying the result print(message)
Explanation:
Variable Assignment:
name is assigned the string value “Omar”.
age is assigned the integer value 20.
Formatting String:
The string message contains placeholders %s and %d, which stand for string and integer formatting, respectively.
%s is a placeholder for the string representation of name.
%d is a placeholder for the integer representation of age.
Using the % Operator:
The % operator is used to format the string. The values to be inserted into the placeholders are provided in a tuple (name, age) after the % operator.
Variable Assignment (cont.):
The formatted string is assigned to the variable message.
Print Statement:
The print statement is used to display the result.
The output will be: My name is Omar and I am 20 years old.
Note:
str.format() method:example with explanation
Here’s an example with an explanation:
# Example: name = "Omar" age = 20 # Using str.format() method message = "My name is {} and I am {} years old.".format(name, age) # Displaying the result print(message)
Explanation:
Variable Assignment:
name is assigned the string value “Omar”.
age is assigned the integer value 20.
Formatting String:
The string message contains placeholders {} inside it. These curly braces serve as placeholders to be replaced by the values provided to the format method.
Using str.format() Method:
The format method is called on the string, and the values to be inserted into the placeholders are passed as arguments to the format method (name and age in this case).
Variable Assignment (cont.):
The formatted string is assigned to the variable message.
Print Statement:
The print statement is used to display the result.
T
he output will be: My name is Omar and I am 20 years old.
# Example with named placeholders
message = “My name is {name} and I am {age} years old.”.format(name=name, age=age)
print(message)
This results in the same output but uses named placeholders for better clarity and organization.
example with explanation
Let’s consider an example where we use the str.format() method to create a formatted string for displaying information about a book:
# Example: book_title = "The Hitchhiker's Guide to the Galaxy" author = "Douglas Adams" publication_year = 1979 price = 12.99 # Using str.format() method to create a formatted string book_info = "Title: {}\nAuthor: {}\nPublication Year: {}\nPrice: ${}".format( book_title, author, publication_year, price ) # Displaying the result print(book_info)
Explanation:
Variable Assignment:
book_title is assigned the string value “The Hitchhiker’s Guide to the Galaxy.”
author is assigned the string value “Douglas Adams.”
publication_year is assigned the integer value 1979.
price is assigned the float value 12.99.
Formatting String:
The string book_info contains placeholders {} inside it. These curly braces serve as placeholders to be replaced by the values provided to the format method.
Using str.format() Method:
The format method is called on the string, and the values to be inserted into the placeholders are passed as arguments to the format method in the specified order (book_title, author, publication_year, and price).
Variable Assignment (cont.):
The formatted string is assigned to the variable book_info.
Print Statement:
The print statement is used to display the result, which contains information about the book.
Output:
Title: The Hitchhiker’s Guide to the Galaxy
Author: Douglas Adams
Publication Year: 1979
Price: $12.99
The format() method in Python allows you to use both positional and keyword arguments for string formatting.
Here’s an example with an explanation:
# Example: product_name = "Laptop" brand = "Dell" price = 1200.50 # Using format() method with positional and keyword arguments product_info = "Product: {0}\nBrand: {brand}\nPrice: ${1:.2f}".format(product_name, price, brand=brand) # Displaying the result print(product_info)
Explanation:
Variable Assignment:
product_name is assigned the string value “Laptop.”
brand is assigned the string value “Dell.”
price is assigned the float value 1200.50.
Formatting String:
The string product_info contains placeholders {0}, {brand}, and {1:.2f} inside it.
{0} and {1:.2f} are positional placeholders for the values of product_name and price, respectively.
{brand} is a keyword placeholder for the value of brand.
Using format() Method:
The format() method is called on the string.
The values for the positional placeholders (product_name and price) are passed as arguments to the format() method in the specified order.
The value for the keyword placeholder (brand) is passed as a keyword argument.
Variable Assignment (cont.):
The formatted string is assigned to the variable product_info.
Print Statement:
The print statement is used to display the result.
Output:
Product: Laptop
Brand: Dell
Price: $1200.50
Template Strings, available in the string module, provide a simple and safe way to perform string substitutions.
Here’s an example with an explanation:
from string import Template # Example: name = "Alice" age = 30 # Using Template Strings template = Template("My name is $name and I am $age years old.") message = template.substitute(name=name, age=age) # Displaying the result print(message)
Explanation:
Importing the Template class:
from string import Template imports the Template class from the string module.
Variable Assignment:
name is assigned the string value “Alice.”
age is assigned the integer value 30.
Creating a Template String:
The Template class is used to create a template string containing placeholders, indicated by the dollar sign ($) followed by the variable names ($name and $age).
Substituting Values:
The substitute() method of the Template class is called on the template string.
Values for the placeholders (name and age) are provided as keyword arguments to the substitute() method.
Variable Assignment (cont.):
The substituted string is assigned to the variable message.
Print Statement:
The print statement is used to display the result.
Output:
My name is Alice and I am 30 years old.
Let’s extend the Template Strings example to include multiple values.
In this example, we’ll create a template for displaying information about a person with multiple attributes:
from string import Template # Example: person_info = { "name": "Omar", "age": 20, "occupation": "Software Developer", "country": "USA" } # Using Template Strings with multiple values template = Template("Name: $name\nAge: $age\nOccupation: $occupation\nCountry: $country") message = template.substitute(person_info) # Displaying the result print(message)
Explanation:
Importing the Template class:
from string import Template imports the Template class from the string module.
Creating a Dictionary with Multiple Values:
person_info is a dictionary containing information about a person, including their name, age, occupation, and country.
Creating a Template String:
The Template class is used to create a template string with placeholders for various attributes ($name, $age, $occupation, and $country).
Substituting Values from the Dictionary:
The substitute() method of the Template class is called on the template string.
The person_info dictionary is provided as an argument to the substitute() method, and its key-value pairs are used to replace the placeholders.
Print Statement:
The print statement is used to display the result.
Output:
Name: Omar
Age: 20
Occupation: Software Developer
Country: USA
Let’s modify the Template Strings example to include index numbers in the placeholders for more explicit control over the substitution:
from string import Template # Example: person_info = { "name": "Alice", "age": 30, "occupation": "Data Scientist", "country": "Canada" } # Using Template Strings with index numbers template = Template("Name: $0\nAge: $1\nOccupation: $2\nCountry: $3") message = template.substitute(person_info.values()) # Displaying the result print(message)
Explanation:
Importing the Template class:
from string import Template imports the Template class from the string module.
Creating a Dictionary with Multiple Values:
person_info is a dictionary containing information about a person, including their name, age, occupation, and country.
Creating a Template String with Index Numbers:
The Template class is used to create a template string with placeholders for various attributes ($0, $1, $2, and $3). These index numbers correspond to the order in which values will be substituted.
Substituting Values from the Dictionary:
The substitute() method of the Template class is called on the template string.
The person_info.values() method is used to provide the values in the order of the index numbers. The values are substituted in the order of appearance in the template.
Print Statement:
The print statement is used to display the result.
Output:
Name: Alice
Age: 30
Occupation: Data Scientist
Country: Canada
Here’s an example with an explanation:
# Example: person_info = { "name": "Bob", "age": 28, "occupation": "Engineer", "country": "United Kingdom" } # Using named indexes in f-string (Python 3.6 and later) message = f"Name: {person_info['name']}\nAge: {person_info['age']}\nOccupation: {person_info['occupation']}\nCountry: {person_info['country']}" # Displaying the result print(message)
Explanation:
Creating a Dictionary with Named Indexes:
person_info is a dictionary containing information about a person with named indexes like “name,” “age,” “occupation,” and “country.”
Using f-string for String Formatting:
The f-string (formatted string literal) is used to create a template string.
Named placeholders (using curly braces {}) are used to reference values from the person_info dictionary directly.
Variable Assignment:
The formatted string is assigned to the variable message.
Print Statement:
The print statement is used to display the result.
Output:
Name: Bob
Age: 28
Occupation: Engineer
Country: United Kingdom
from string import Template def generate_welcome_email(_info): # Define a template for the email body email_template = Template(""" Dear $name, Welcome to our community! We are excited to have you on board. Your account details: - name: $name - Email: $email If you have any questions or need assistance, feel free to reach out. Best regards, The Community Team """) # Use the template to generate the personalized email body email_body = email_template.substitute(_info) return email_body # Example information _information = { "name": "Omar AboBakr", "name": "OmarAboBakr123", "email": "OmarAboBakr@example.com" } # Generate the welcome email welcome_email = generate_welcome_email(_information) # Displaying the result print(welcome_email)
Explanation:
Creating a Template for the Email Body:
The email_template is a multi-line string template using the Template class. It contains placeholders like $name, $name, and $email for -specific information.
Defining a Function for Email Generation:
The generate_welcome_email function takes a dictionary _info as input, which includes -specific details like name, name, and email.
Using the Template to Generate Email Body:
The substitute method of the Template class is used to substitute the placeholders in the template with values from the _info dictionary.
Variable Assignment:
The generated email body is assigned to the variable email_body.
Displaying the Result:
The print statement is used to display the personalized welcome email.
Output:
Dear Omar AboBakr,
Welcome to our community! We are excited to have you on board.
Your account details:
– name: OmarAboBakr123
– Email: OmarAboBakr@example.com
If you have any questions or need assistance, feel free to reach out.
Best regards,
The Community Team
Each question has multiple-choice answers, and the correct answer is indicated in parentheses.
A. Combining integers
B. Joining lists
C. Creating strings with variables (Correct Answer)
D. Sorting strings
A. *
B. + (Correct Answer)
C. /
D. –
A. Integer
B. Float
C. String (Correct Answer)
D. List
A. Sorting strings
B. Concatenating strings
C. String formatting (Correct Answer)
D. Converting strings to lowercase
A. Compatibility with Python 2
B. Improved readability and conciseness (Correct Answer)
C. Better performance for large strings
D. Limited functionality
A. substitute (Correct Answer)
B. replace
C. format
D. insert
A. $
B. %
C. @
D. {} (Correct Answer)
A. Regular expression support
B. String interpolation
C. Safe string substitutions (Correct Answer)
D. Advanced string manipulation
A. {position}
B. {$position}
C. {0} (Correct Answer)
D. $0
A. $1, $2, …
B. {1}, {2}, …
C. $name, $age, … (Correct Answer)
D. {name}, {age}, …
A. template.replace()
B. template.sub()
C. template.substitute() (Correct Answer)
D. template.format()
A. Python 2.7
B. Python 3.2
C. Python 3.6 (Correct Answer)
D. Python 3.0
A. Indicate the end of the string
B. Represent a placeholder (Correct Answer)
C. Multiply two values
D. Escape special characters
A. { }
B. {{ }} (Correct Answer)
C. {}
D. `$ { } $
A. Double
B. Decimal integer (Correct Answer)
C. Date
D. Dictionary
A. Better performance
B. Improved readability
C. Safer substitutions (Correct Answer)
D. Greater flexibility
A. {:2f}
B. {:2}
C. {:.2f} (Correct Answer)
D. {:2.0f}
A. f”Hello, {name}!” (Correct Answer)
B. f’Hello, {name}!’
C. “Hello, {name}!”.format()
D. “Hello, {name}!” % name
A. SyntaxError
B. NameError (Correct Answer)
C. TypeError
D. ValueError
A. join()
B. concat()
C. + (Correct Answer)
D. merge()