String is one of basic variable types with capabilities to customize and manipulate its value.

Here are 3 ways we can make a string template in Python.


1. f-string

A super basic. Just start the string value with f and write {} around the value we want to place inside the string and done.

For example,

Start with f followed by any types of quote pairs; single-quotes '', double-quotes  "", triple single-quotes '''''', or even triple double-quotes """""", depends on whether we need to have any escaped quote characters inside the string.

  • If we have multiple lines of the string, consider triple single-quotes or triple double-quotes.
  • If we have single-quotes in the string, consider double-quotes for f-string or vice-versa.

And specify variables inside {} in the f-string.

Even though it looks so simple yet there are plenty formats we can apply. Read more here.

7. Input and Output
There are several ways to present the output of a program; data can be printed in a human-readable form, or written to a file for future use. This chapter will discuss some of the possibilities. Fa…

2. String template

There is an innate library we can use to format a string in a more flexible way without installing any third-party libraries. It is a string template.

Just from String import Template and it's ready.

Specify variables using $ and the variable name. Then substitute using .substitute() to format the string with variables or .safe_substitute() to avoid errors if some specified variables in the string are not supplied in parameters.

Parameters can be either keywords (key=value) or dict of key-value pairs ({"key":"value"}).

Read more here.

string — Common string operations
Source code: Lib/string.py String constants: The constants defined in this module are: Custom String Formatting: The built-in string class provides the ability to do complex variable substitutions…

3. Jinja

It must be a case we need more advance formatting and there always be an external library for us.

It's Jinja2 library.

Jinja — Jinja Documentation (3.1.x)

In short, we can use this library to design string formatting with more complex conditions. But for this blog we make just an intro for this.

Start from install this library, pip install jinja2. And use it like this.

With .render() we supply the parameter variables specified in {{}} in the template.

Parameters can be either keywords or dict of key-value pairs.