3 ways for Python string template

bluebirz
2 min readJul 21, 2024

--

also available at
[EN]
https://www.bluebirz.net/en/3-ways-to-format-strings/
[TH]
https://www.bluebirz.net/th/3-ways-to-format-strings-th/

Photo by Anya Chernik on Unsplash

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.

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.

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.

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.

--

--