Sling Academy
Home/Python/4 Ways to Format a String in Modern Python

4 Ways to Format a String in Modern Python

Last updated: May 24, 2023

Using f-strings or formatted string literals (Python 3.6+)

This method allows you to embed variables and expressions directly into string literals by prefixing the string with f (that’s why the term f-strings was born). Variables and expressions enclosed in curly braces {} are evaluated, and their values are inserted into the string.

Example:

name = "Robinson Crusoe"
age = 99
message = f"My name is {name} and I am {age} years old. Next year, I will be {age + 1} years old."

print(message)

Output:

My name is Robinson Crusoe and I am 99 years old. Next year, I will be 100 years old.

In general, f-strings are considered the most modern and preferred way of string formatting in Python, as they are concise, expressive, and fast.

Using the str.format() method

This approach allows you to create formatted strings by calling the format() method on a string and passing values to be inserted. Placeholder curly braces {} in the string are replaced with the provided values in the order they appear.

Example:

name = "Mr. Turtle"
age = 100
message = "They call me {} and I am {} years old.".format(name, age)
print(message)

Output:

They call me Mr. Turtle and I am 100 years old.

You can also use the str.format() method with positional placeholders by specifying the positions of the values to be inserted using curly braces {} with indices inside:

name = "Wolf"
age = 35
message = "My name is {0} and I am {1} years old.".format(name, age)
print(message)

Output:

My name is Wolf and I am 35 years old.

Besides positional placeholders, you can assign names to the placeholders by using named arguments in the format() method. Below is an example of using named placeholders:

name = "Wolf"
age = 35
message = "My name is {name} and I am {age} years old.".format(name=name, age=age)

print(message)

Output:

My name is Wolf and I am 35 years old.

Using the % operator (legacy)

This old-fashioned method uses the % operator to format strings similar to the C language’s printf-style formatting. The formatting string contains placeholders %s and %d that are replaced with the provided values.

Example:

product = "Dog Food"
price = 49.99
description = "This product is is %s and its price is %d bucks." % (product, price)

print(description)

Output:

This product is is Dog Food and its price is 49 bucks.

This method is less and less used in new Python projects because of its cumbersomeness and lack of convenience.

Using the Template class

This is a less common way of string formatting in Python, and it uses the Template class from the string module to create template strings that can be substituted with values from a dictionary.

Example:

from string import Template
name = "Wolf"
age = 35
t = Template("Hello, $name. You are $age years old.")
print(t.substitute(name=name, age=age))

Output:

Hello, Wolf. You are 35 years old.

Next Article: Python: 5 Ways to Reverse a String

Previous Article: Python: 7 Ways to Find the Length of a String

Series: Working with Strings in Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots