Python language basics 39: string formatting

Introduction

In the previous post we looked at the usage of the partition function. It can be applied to strings and it breaks up strings into 3 parts: to the left and the right of the partitioner and the partitioner itself. It is similar to the split function.

In this post we’ll briefly go through formatting strings with the format function.

Formatting strings

By string format we mean how we want to show, i.e. format a string in the user interface. You’ll often encounter string formats in conjunction with cultural settings. E.g. time, dates, currencies, numbers etc. are shown differently in Japan than in the US or in France. Different users in different regions will prefer to see those values as they understand them.

Formatting strings is a large topic. Here we’ll only go through the basics. This documentation page will be a good friend of yours for a more complete reference.

The format functions can be called upon a string which is the format itself with one or more placeholders. The function accepts one or more arguments that will be substituted into those placeholders. The placeholders are delimited by the ‘{‘ and ‘}’ characters and they can be as simple as an empty placeholder {} or more complex and cryptic such as ‘{:+f}’ or ‘{:%Y-%m-%d %H:%M:%S}’.

Let’s start with the positional arguments. Positional arguments are provided as integers within the format placeholders. The integers will be substituted based by the values provided as the arguments to the format function. Here’s a simple example:

format = "My name is {0}, I come from {1} and currently live in {2}"
formatted = format.format("John", "England", "Birmingham")
print(formatted)

This prints “My name is John, I come from England and currently live in Birmingham”. Note that the integer placeholders are 0-based like collection indexers. 0 was replaced by the first element “John”, 1 by “England” and 2 by “Birmingham”.

You can reuse the string elements multiple times:

format = "My name is {0}, I come from {1} and currently live in {2}. I repeat, my name is {0}"
formatted = format.format("John", "England", "Birmingham")
print(formatted)

…where ‘formatted’ evaluates to “My name is John, I come from England and currently live in Birmingham. I repeat, my name is John”, i.e. “John” was used twice.

In the first example we simply substituted the individual arguments one by one into the placeholders in the same order as they appear. If that’s all you need then you can just leave the placeholders empty:

format = "My name is {}, I come from {} and currently live in {}"
formatted = format.format("John", "England", "Birmingham")

We can also refer to the placeholders by names:

format = "My current geographical position is {city}, {country}, {continent}."
formatted = format.format(city="Stockholm", country="Sweden", continent="Europe")

We can even retrieve those from a collection like a [list] or a [tuple]:

geo_args = ["Stockholm", "Sweden", "Europe"]
format = "My current geographical position is {geo_args[0]}, {geo_args[1]}, {geo_args[2]}"
formatted = format.format(geo_args=geo_args)

The string format mini-language is a science in itself. Refer to the above Python reference document for a myriad of cases ranging from date and time to currencies and numeric values.

View the next post in this series here.

Read all Python-related posts on this blog here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: