Skip to content
Home » Programming » String Formatting and Templates in Python

String Formatting and Templates in Python


In this post, we will be investigating the linguistic structure of the String Formatting and Templates in Python. At first, let us start with the string formatting in Python and then we will jump to the String Templates in Python.

String Formatting

Python provides a sophisticated formatting system for strings that can be useful for printing information out or logging information from a program.

We will discuss the string formatting system uses a special string known as the format string that acts as a pattern defining how the final string will be laid out. The format string can contain placeholders which is replaced with actual values after creation of the final string. A set of values can be applied to the format string to fill the placeholders using the format() method.

Moreover, the simplest example of a format string is one that provides a single placeholder indicated by two curly braces (e.g. {}). For example, the following is a format string with the pattern ‘Hello’ followed by a placeholder.

format_string = 'Hello {}!'

This can be used with the format() string method to provide a value (or populate) the placeholder, for example,

print (format_string.format('DroxElement'))

The output from this is as given below.

Hello DroxElement!

Moreover, a format string can have any number of placeholders that must be populated, for example the next example has two placeholders that are populated by providing two values to the format() method.

# Allows multiple values to populate the string
name = 'Adam'
age = 20
print ('{} is {} years old'.format(name, age))

In this case, the output is

Adam is 20 years old

It also illustrates that variables can be used to provide the values for the format method as well as literal values. But a literal value is a fixed value such as 42 or the string ‘John’.

By default, the values are bound to the placeholders based on the order that they are provided to the format() method; however this can be overridden by providing an index to the placeholder to tell it which value should be bound. For example,

# Can specify an index for the substitution
format_string = 'Hello {1} {0}, you got {2}%'
print (format_string.format('Drox','Element',100))

In this case, the second string ‘Element’ will be bound the first placeholder; note that the parameters starts numbering from zero.

The output from the above example is:

Hello Element Drox, you got 100%

Importantly, when ordering the values it is quiet easy to get something wrong either. Because a developer might think the strings are indexed from 1 or just because they get the order wrong.

An alternative approach is to use named values for the placeholders. In this approach the curly braces surround the name of the value to the substituted, for example {artist}. Then in the format() method a key = value pair is provided where the key is the name in the format string.

# Can use named substitutions, order is not significant
format_string = '{artist} wrote {article} in {year}'
print (format_string.format (artist = 'DroxElement', article = 'Python Program', year = 2020))

In this example, the order no longer matters as the name associated with the parameter passed into the format() method is used to obtain the value to be substituted. In this case, the output is

DroxElement wrote Python Program in 2020

It is possible to indicate alignment and width within the format string. For example, if we wish to indicate a width to be left for a placeholder whatever the actual value supplied. We can do this using a colon (‘:‘) followed by the width to use. For example, to specify a gap of 25 characters which can be filled with a substitute value we can use {:25} as shown below.

print ('|{:25}|'.format('DroxElement'))

In the above snippet, the vertical bars are to indicate where the string starts and ends for reference, they have no meaning within the format method. This produces the output;

|DroxElement              |

Within this gap we can also indicate an alignment where:

  • < indicates left alignment (the default),
  • > indicates right alignment,
  • ^ indicates centered

These follow the colon (‘:‘) and come before the size of the gap to use, for example,

print ('|{:<25}|'.format('left aligned')) # The default
print ('|{:>25}|'.format('right aligned'))
print ('|{:^25}|'.format('centered'))

which produces;

|left aligned             |
|            right aligned|
|        centered         |

In order to format a number with separators (such as comma) to indicate thousands there is another formatting option shown below.

# Can format numbers with comma as thousands separator
print ('{:,}'.format(1234567890))
print ('{:,}'.format(1234567890.0))

which generates the output as


There are in fact numerous options available to control the layout of a value within the format string and the Python documentation should be referenced for future information.

Also Read: String Functions in Python

String Templates

An alternative to using string formatting is to use string Templates. These came in action from Python 2.4 as a simpler, less error prone, solution to most string formatting requirements.

A string template is a class that is created via the string.Template() function. The template contains one or more named variables preceded with a $ symbol. Then the template is used with a set of values replacing the template variables with actual values. For example,

import string

# Initialize the template with $variables that will be substitute with actual values
template = string.Template ('$artist wrote $article in $year')

It is necessary to include an import statement at the start of the program since Templates are not provided by default in Python; they must be loaded from a library of additional string features. This library is part of Python but we need to tell Python that we want to access these extra string facilities.

The string passed into the string.Template() function can contain any characters plus the template variables (which are indicated by the $ character followed by the name of the variable such as $artist above).

template = string.Template ('$artist wrote $article in $year')

The above is thus a template for the pattern ‘some-artist wrote some-article in some-year‘.

The actual values can be substituted into the template using the substitute() function. The substitute function takes a set of key = value pairs. In which the key is the name of the template variable (minus the leading $ character) and the value is the value to use in the string.

print (template.substitute (artist = 'DroxElement', article = 'Python Program', year = 2020))

In this example, $artist will be replaced by the ‘DroxElement’, $article by ‘Python Program’ and $year by 2020. The substitute function will then return a new string containing

'DroxElement wrote Python Program in 2020'

This is illustrated in the following code snippet.

import string

# Initialize the template with $variables that will be substituted with actual values
template = string.Template ('$artist wrote $article in $year')

# Substitute template variables with actual values
# Can use a key = value pairs where the key is the name of the template variable and the value is the value to use in the string
print (template.substitute (artist = 'DroxElement', article = 'Python Program', year = 2020))

This produces

DroxElement wrote Python Program in 2020

Moreover, we can reuse the template by substituting other values for the template variables, each time we call the substitute() method it will generate a new string with the template variables replaced with the appropriate values.

print (template.substitute (artist = 'DroxElement', article = 'C Program', year = 2020))
print (template.substitute (artist = 'DroxElement', article = 'C# Program', year = 2020))

With the above producing;

DroxElement wrote C Program in 2020
DroxElement wrote C# Program in 2020

Alternatively we can create a dictionary. A dictionary is a structure with the structure of key:value pairs in which the key is unique. This allows to create a data structure containing the values to use and then applied to the substitute function.

d = dict(artist = 'DroxElement', article='Data Structure & Algorithms',
year = 2020)
print (template.substitute(d))

This produces a new string as

DroxElement wrote Data Structure & Algorithms in 2020

Template strings can contain template variables using the format $name-of-variable; however there are a few variations that are worth noting.

  • $$ allows to include a ‘$’ character in the string without Python interpreting it as the start of a template variable; the double ‘$$’ is replaces with a single $. This is known as escaping a control character.
  • ${template_variable} is equivalent to $template_variable. It is necessary when valid identifier characters follow the placeholder but are not part of the placeholder, such as ‘${noun}fiction’.

Another point to note about the template.substitute() function is that if we fail to provide all the template variables with a value then an error will be generated. For example,

print (template.substitute (artist = 'DroxElement', article = 'Python Program'))

Conclusively, this will result in the program failing to execute and an error message.

This is because the template variable $year has not been provided with a value. If we do not want to have to worry about providing all the variables in a template with a value then we should use the safe_substitute() function.

print (template.safe_substitute (artist = 'DroxElement', article = 'Python Program'))

This will populate the template variables provided and leave any other template variables. For example, for above code snippet the output is

DroxElement wrote Python Program in $year

To download Python supported IDE (Visual Studio Code), click here!

Leave a Reply

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