How to format strings in Python?

This article provides a comprehensive overview of string formatting in Python along with examples. But why is string formatting important? Imagine you have a string, and you wish to present it in a more organized and understandable manner. Let’s consider a straightforward scenario involving date and time formatting. In such cases, the goal is to structure your string to accurately represent data, like dates or times, for improved readability. String formatting is a fundamental aspect of Python programming, playing a pivotal role in code clarity and user interaction. Throughout this article, we’ll discuss various techniques and functions used to format strings in Python. So, let’s dive into the article details!

Methods to format strings in Python

Python offers flexibility when it comes to string formatting within Python scripts. Here is a list of methods discussed in this article:

  • Using the format Operator (%) to format strings
  • Using str.format() function for string Formatting
  • Using f-Strings to format a string in Python
  • Using Template Strings for String Formatting

Using the format Operator (%) to format strings

In Python, the format operator, represented by the % symbol, is used for string formatting. It allows you to construct strings by replacing parts of the strings with data stored in variables. Placeholders within the string serve as positions where dynamic content will be inserted during string formatting.

Here are some common placeholder formats:

  1. %s: for inserting strings.
  2. %d: for inserting integers.
  3. %f: for inserting floating-point numbers (decimal numbers).
  4. %x: for inserting integers in hexadecimal format.
  5. %o: for inserting integers in octal format

When you apply the format operator to a template string, these placeholders are replaced with actual values or variables, resulting in a well-structured and formatted string that incorporates dynamic data.

The syntax for formatting strings in Python using the % operator is quite straightforward and is as follows:


'some string %s remaining string' % (original string to be inserted for formatting)

The above string includes %s placeholder which will be replaced by the value provided in the parentheses. This allows you to incorporate dynamic content into a string.

Lets consider an example. Suppose we have two variables i.e., ‘company_name’ and ’employeeID’. Lets display them in a string using string formatting.


company_name = 'Entechin'

employeeID = 247

print('Your company is %s.'%company_name)

print('Your employee ID is %d.'%employeeID)

Output:

Your company is Entechin.
Your employee ID is 247.

You can also use multiple placeholders in a single string as shown below:

details= 'Your company name is %s, and your ID is %d.'%(company_name, employeeID)

print(details)

Output:

Your company name is Entechin, and your ID is 247.

This approach is especially useful for creating user-friendly output, generating log messages, or composing complex textual output in your Python programs.

Using str.format() function for string Formatting 

The format() function can also be used for creating customized and structured strings with placeholders. It allows you to create template strings with placeholders represented by curly braces {}. When you call format() function, these placeholders are replaced with the values specified as arguments in the function. Placeholders can be identified using various methods, such as named indexes, numbered indexes {0}, or even empty placeholders {}.

Here’s an overview of how format() placeholders work:

Empty Placeholders {}:

Sometimes, you might not need to specify an index or name, especially when the order of arguments matches the order of placeholders in the string. Consider an example in which we have variables representing book details like the title, author and price. In this example, we will use the format() method to insert these variables into a formatted string, which includes line breaks (\n) to make it more readable. The price is formatted to display two decimal places using :.2f.

# Book details
book_title = "The Great Gatsby"
author = "F. Scott Fitzgerald"
price = 12.99

# Create a formatted string to display book details
book_info = "Title: {}\nAuthor: {}\nPrice: ${:.2f}".format(book_title, author, price)

# Print the formatted book information
print("Book Information:\n")
print(book_info)

Output:

Book Information:

Title: The Great Gatsby
Author: F. Scott Fitzgerald
Price: $12.99

Named Placeholders:

You can assign names to placeholders to make your code more readable and self-explanatory. For example, you might have placeholders like {name}, {age}, and {city}.

Here’s the code to demonstrate how we can use named placeholders for string formatting:

# Create a formatted string to display book details
book_info = "Title: {title}\nAuthor: {writer}\nPrice: ${cost:.2f}".format(title=book_title, writer=author, cost=price)

# Print the formatted book information
print("Book Information:\n")
print(book_info)

Output:

Book Information:

Title: The Great Gatsby
Author: F. Scott Fitzgerald
Price: $12.99

In this example, we use named placeholders {title}, {writer}, and {cost} and provide corresponding names in the format() method to specify the values for these placeholders.

Numbered Placeholders:

You can use numbered placeholders such as {0}, {1}, etc. where {0} represents the first argument, {1} represents the second, and so on. These numbered placeholders represent the position of the values in the format() method argument list.

# Using numbered indexes as placeholders
book_info = "Title: {0}\nAuthor: {1}\nPrice: ${2:.2f}".format(book_title, author, price)

# Print the formatted book information
print("Book Information:\n")
print(book_info)

Output:

Book Information:

Title: The Great Gatsby
Author: F. Scott Fitzgerald
Price: $12.99

In the above example, the numbers inside the placeholders indicate the index of the argument to use for replacement.

You can also use the data in a dictionary to insert into a string using format() function as follows:

dictionary= {'Players': 'Fakhar Zaman','Runs': '193'}

print("The player {info[Players]} scores {info[Runs]} in WC.".format(info=dictionary))

Output:

The player Fakhar Zaman scores 193 in WC.

In summary, the choice of which type of placeholder to use depends on your specific use case. Numbered placeholders are explicit and useful for maintaining argument order. Named placeholders improve code readability and are flexible. Empty placeholders are the simplest but provide the least context. Consider your code’s readability, maintainability, and specific formatting requirements when choosing the appropriate type of placeholder for your situation.

Using f-Strings to format a string in Python

Another concise way to format strings is by using formatted string literals, often referred to as f-strings. With f-strings, you can directly embed expressions and variables within string literals by prefixing them with ‘f’ or ‘F’. This method provides a readable and efficient way to create formatted strings. The f-string is prefixed with the letter ‘f’ or ‘F’. Inside an f-string, you can include expressions enclosed in curly braces {}. These expressions are evaluated at runtime and their values are inserted into the string.

Let’s understand through an example:

name = input("Enter your name: ")

print(f"Hey {name}! Welcome to Entechin.")

Output:

Enter your name: Aliza
Hey Aliza! Welcome to Entechin.

In this example, the variable name is directly inserted in the string using the {} placeholders within the f-string.

The f-strings in Python can also be used to create formatted strings that include the results of a certain expression evaluation. For the expression evaluation, you can use list comprehension or lambda functions. For example, suppose you have a list of numbers and you want to create a string that lists each number and its cube.

numbers = [1, 2, 3, 4, 5]

# Create a formatted string using an f-string 
result = "\n".join([f"Number: {num}, Cube: {num**3}" for num in numbers])

# Print the result
print(result)

Output:

Number: 1, Cube: 1
Number: 2, Cube: 8
Number: 3, Cube: 27
Number: 4, Cube: 64
Number: 5, Cube: 125

The above code uses a list comprehension to iterate through the numbers, applies the cube calculation and displays the formatted string.

Using Template Strings for String Formatting

Template Strings is an inbuilt module in Python for string formatting. These templates are used within parentheses, and they include placeholders indicated by the dollar sign ($) followed by valid Python identifiers. These placeholders serve as names for data that will be inserted into the string. The following example demonstrates how we can use the Python’s string.Template for string formatting:

from string import Template

# Define variables
name = "Aliza"
account_balance = 80000.25
cash_withdrawal = float(input('Enter the amount you want to withdraw: '))
balance = account_balance - cash_withdrawal

# Create a template string
template = Template("Hello, $name! You have withdrawn $$${cash}. Your current balance is $$${balance}")

# Substitute values into the template
formatted_string = template.substitute(name=name, cash=cash_withdrawal, balance=balance)

# Print the formatted string
print(formatted_string)

Output:

Enter the amount you want to withdraw: 9650
Hello, Aliza! You have withdrawn $9650.0. Your current balance is $70350.25

The above code takes user input for a cash withdrawal. The new balance is calculated and inserted into a string using a template string.

Conclusion

In this guide, we’ve explored various methods for formatting strings in Python, each accompanied by illustrative examples. It’s important to choose the approach that aligns best with your specific requirements and coding style. By mastering these string formatting techniques, you can make your Python code more elegant, readable, and user-friendly. Select the method that best suits your task, and create well-formatted strings to convey information effectively. Check out this tutorial to see how can we insert integers into a string.

If you want to learn more about Python Programming, visit Python Programming Tutorials.

Leave a Comment

Your email address will not be published. Required fields are marked *