Python provides excellent support for string op­er­a­tions and text pro­cess­ing. The language has com­pre­hen­sive methods for for­mat­ting and out­putting text. We’ll give you an overview of the most important methods for Python string for­mat­ting.

What are the string format methods in Python used for?

Strings are sequences of char­ac­ters, and they can contain single letters, words, sentences or entire documents in Python. Methods are needed to format strings.

Strings can consist of several pieces. In many cases, the static string com­po­nents and variable data should be mixed. This is required when out­putting data and creating documents in web de­vel­op­ment.

Let’s use an online store as an example. We want to calculate the total price of the products in a user’s shopping cart and show it to them using the following message: “The total price is […] dollars.” The first step would be to assemble the string using the con­cate­na­tion operator:

price = 69.42
message = "The total price is" + price + "USD".
Python

An error message is displayed because the price is a number and cannot be con­cate­nat­ed with a string. We have to convert the number to a string using the str() function first:

message = "The total price is" + str(price) + "USD".
Python

This can get confusing, so it’s better to define the entire text including the place­hold­er and fill it with data. You may have to adjust the for­mat­ting when con­vert­ing the data. The Python string format methods can help you to do this.

How do Python string format methods work?

Python supports several string format methods, each with its own ad­van­tages and dis­ad­van­tages. The number of methods has grown over time, which means that there are many sim­i­lar­i­ties and some dif­fer­ences between the in­di­vid­ual methods. We’ll present the four most popular ap­proach­es to Python string for­mat­ting:

  1. String for­mat­ting with the modulo operator
  2. String for­mat­ting with the str.format() method
  3. String for­mat­ting with string in­ter­po­la­tion
  4. String for­mat­ting with template strings

Modulo operator

This oldest string for­mat­ting in Python uses the Python operator for per­cent­age signs, which is used for the math­e­mat­i­cal modulo operation. This approach is also known as modulo string for­mat­ting.

We’ll use a scheme with three variables in the following example. The actual names are not important and were chosen to make the code easier to follow.

Component Des­ig­na­tion
String template with place­hold­er(s) Template
Modulo operator %
Data to be inserted Data
Completed formatted string message

First, we must define the template as a string variable with the name template. We then define the place­hold­er’s position with the ab­bre­vi­a­tion %s in the template:

template = "The total price is %s"
Python

Then, we define the value to be inserted as a variable called data:

data = 69.51
Python

To perform Python string for­mat­ting, we write the string template followed by the modulo operator and the data variable. We also need to assign the formatted string to the message variable:

message = template % data
Python

The data can be a variable. But we can also use a literal, or an ex­pres­sion. The modulo operation can be placed on a single line. This is an example with a string literal instead of a place­hold­er:

message = "Here comes %s" % "Jack"
Python

In the following example, we’ll calculate the sum of the in­di­vid­ual prices and insert the total price into the message. The same scheme takes effect; showing that an ex­pres­sion may follow the modulo operator:

prices = (42, 69, 51)
message = "The total price is %s" % sum(prices)
Python

You may be wondering why %s is used as the place­hold­er instead of just the percent sign. The “s” has a special meaning. It is converted into a string using the str() function when the data is inserted.

There are other string for­mat­ting shortcuts in Python, which focus on for­mat­ting numbers. To il­lus­trate this, we’ll use pi in the following example. The number is placed into the place­hold­er %s. The output contains 15 decimal places:

from math import pi as PI
print("The value of Pi is approximately %s" % PI)
Python

If we use the ab­bre­vi­a­tion %g as a place­hold­er instead, only five decimal places will be displayed:

print("The value of Pi is approximately %g" % PI)
Python

A number of other options are available, and we’ll describe these in the following section.

With Python’s modulo string for­mat­ting, you can also define and populate multiple place­hold­ers. In this case, the modulo operator expects a tuple with as many values as there are place­hold­ers. The place­hold­ers are filled with the values:

person = ('John', 42)
message = "My friend %s is %s years old" % person
Python

The Python string for­mat­ting with modulo operator is not very easy to read. It becomes simpler if we pass a dict with the data instead of a tuple. We must enter the dict entries’ names between the brackets after the place­hold­er’s percent sign. Doing this makes it easier to recognize values when reading the string template:

person = {'name': 'John', 'age': 42}
message = "My friend %(name)s is %(age)s years old" % person
Python

str.format() method

Python’s string format method is an im­prove­ment on the modulo for­mat­ting that was orig­i­nal­ly included in Python 3 and later carried over to Python 2.6. An object-oriented approach is used instead of a special operator. This makes str.format() con­sis­tent with the other string methods, such as Python’s str.split function.

The Python str.format() method’s basic scheme is similar to for­mat­ting with the modulo operator and can be found in a similar form in .NET and Rust. Curly braces are used as place­hold­ers in the template string and the data is passed as arguments to the function call:

template = "Here comes {}"
data = 'Jack'
message = template.format(data)
Python

If the template string contains multiple place­hold­ers, a cor­re­spond­ing number of arguments must be passed:

message = "My friend {} is {} years old".format('John', 42)
Python

We can choose to specify the position of the arguments to include them as indexes. This allows us to decouple the place­hold­ers’ order from the arguments. Remember that indexes start at zero:

message = "My friend {1} is {0} years old".format(69, 'Jim')
Python

If the in­di­vid­ual values are in a data structure, we should use an asterisk operator before the argument to unpack the data structure. This works with lists and tuples:

person = ('John', 42)
message = "My friend {} is {} years old".format(*person)
Python

The blank place­hold­ers can get confusing with longer strings. It is better to use named arguments:

template = "My friend {name} is {age} years old"
message = template.format(name = 'Jack', age = 51)
Python

If you have too many values, the argument list becomes long and confusing. It is better to combine the values in a dict and unpack the dict when calling the function. To unpack a dict, a double asterisk needs to be used:

# define dict
person = {'name': 'Jim', 'age': 69}
# define string with placeholders
template = "My friend {name} is {age} years old"
# unpack dict in `format()` call
message = template.format(**person)
Python

The wide range of for­mat­ting options is what makes for­mat­ting Python string with str.format() special. It extends the func­tion­al­i­ty of modulo for­mat­ting and is es­pe­cial­ly powerful for out­putting text on the command line as well as when used for tabular data. Now, we’ll look at how to use the mechanism for for­mat­ting numbers.

Python ensures precise control when out­putting numbers as text. For example, you can specify how the numbers’ signs should be displayed. The number of decimal places can also be specified for decimal numbers. This is useful when dis­play­ing positive or negative numbers in a table.

Let’s imagine we want to output tem­per­a­ture mea­sure­ments:

samples = [('A0147D', 27.6), ('X1489M', -4.7), ('P9921U', -10.93)]
for sample in samples:
    print('| {} |'.format(*sample))
Python

The output looks chopped up because the numbers are different lengths:

| A0147D | 27.6 |
| X1489M | -4.7 |
| P9921U | -10.93 |
Bash

Now, we’ll customize the code and define a set of for­mat­ting options:

for sample in samples:
    print('| {} | {: 6.2f} |'.format(*sample))
Python

The output fits now:

| A0147D | 27.60 |
| X1489M | -4.70 |
| P9921U | -10.93 |
Bash

Let’s take a closer look at the for­mat­ting options of the second place­hold­er. These come after the colon and have four com­po­nents:

  1. Space: Comes before positive numbers to com­pen­sate for the space taken by the minus sign for negative numbers
  2. Number before the dot: Total number of letters available for the number
  3. Number after the dot: Number of digits after the decimal point, fills with zeros if necessary
  4. Letter “f” before the closing curly bracket: Formats the number as a decimal number

There are a number of other for­mat­ting options that can be used to control the output of numbers and strings. They are not used very often, but if you need to use them, consult the official Python string for­mat­ting doc­u­men­ta­tion.

String in­ter­po­la­tion

String in­ter­po­la­tion has been available as a for­mat­ting method since Python 3.6. The approach is also known as “f-strings” and it is the most con­ve­nient and per­for­mant for many scenarios. The name comes from the general syntax. F-strings start with the letter “f”, which is placed directly before the opening quotation marks.

Curly braces are used as place­hold­ers. Unlike the methods presented so far, the place­hold­ers contain an ex­pres­sion rather than an index or name. The place­hold­ers are filled im­me­di­ate­ly when defining the f-string:

message = f "40 + 2 equals {40 + 2}"
Python

The ex­pres­sion can also be a variable’s name:

name = 'Jack'
message = f "Here comes {name}"
Python

Multiple ex­pres­sions can be included:

prices = (42, 69, 51)
currency = 'EUR'
message = f "The total price is {sum(prices)} {currency}"
Python

Template strings

Python also supports string for­mat­ting with template strings. These are generated from a separate class and provide pro­tec­tion against security vul­ner­a­bil­i­ties when for­mat­ting user strings.

The for­mat­ting options within template strings are limited. The place­hold­ers may only contain variable names, which are used instead of ex­pres­sions. Template strings are simple, and they are well suited to the in­ter­na­tion­al­iza­tion of strings, which are available in multiple languages.

A dollar sign followed by the variable’s name is used as a place­hold­er. This makes template strings similar to a shell language’s syntax, such as Bash or Zsh. The value is inserted when the sub­sti­tute() method is called:

# import `template` class from `string` module
from string import template
# instantiate template
template = Template("Hey there, I'm $name")
# perform substitution
message = template.substitute(name = 'Jack')
Python

Another syntax for place­hold­er is the dollar sign followed by curly braces that contain the variable’s name. This allows sub­sti­tu­tions to be made within a word:

template = Template("Let's buy $amount ${fruit}s")
message = template.substitute(amount = 3, fruit = 'orange')
Python

Which Python string format method should I choose?

Below we have sum­ma­rized the in­di­vid­ual methods and included relevant details about each one:

Method Scheme Place­hold­er Benefit
Modulo for­mat­ting template % data %, %(key) Python version < 2.6
str.format() template.format(data) {}, {index}, {key} Complex for­mat­ting
f-string f“{ex­pres­sion}“ {ex­pres­sion} Extensive strings
Template string template.sub­sti­tute(data) ${iden­ti­fi­er} If the strings come from the user side
Go to Main Menu