Sitemap
Data Visualization, Data Science and Python

Practical hands-on articles and tutorials about Data visualisation, Data Science, AI and other topics. Mostly in Python.

Member-only story

String Formatting in Python3

4 min readNov 23, 2021

--

Press enter or click to view image in full size
Photo by Steve Johnson on Unsplash

I don’t use Python string formatting very much and, until recently, I’ve just used the C-style formatting that has been with Python since the year dot.

But, a while ago, I wanted to format some SQL queries that used the same string several times and I was slightly offended by the code that I had to write. So, I decided that I really ought to get up to date and start using the formatting that has been around since the beginning of Python3 and then, maybe, get modern and look at the f-strings that were introduced in 3.6.

To remind you of the original string formatting mechanism here’s a bit of code:

name1 = 'Mickey'
print('Is that mouse called %s?' %name1)

The %s is replaced with the string that follows the % sign after the end of the string. So you get:

Is that mouse called Mickey?

That is very straightforward and easy to write if not terribly Pythonic.

If you want more than one string you need to put the list of strings in a tuple and they will be used in the order that they are listed. And that is where things start to get a little bit ugly, especially if you use the same string twice.

--

--

Alan Jones
Alan Jones

Written by Alan Jones

I have had many years of experience in software development and was also a university teacher. I now write about AI, data science and programming.

Data Visualization, Data Science and Python
Data Visualization, Data Science and Python

Published in Data Visualization, Data Science and Python

Practical hands-on articles and tutorials about Data visualisation, Data Science, AI and other topics. Mostly in Python.