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.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

My goal with this blog is to offend everyone in the world at least once with my words… so no one has a reason to have a heightened sense of themselves. We are all ignorant, we are all found wanting, we are all bad people sometimes.

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: