Python – String Formatting

Creating a string using variables is not a complex task but when chaining variables together it is very easy to make a mess of a few lines of code just to create a string you want to use in your program. In this post I outline a few ways you can format your string to not only make it easier to read and understand but do some more complex things fairly easily.

 

In this post I will show you ways of creating strings with multiple variables, dictionaries, and lists

 

Scenario: Lets say I have a script that is gathering data from somewhere and the data it is gathering will be a first name, last name, and their age and those are passed to a function that prints the information to the screen in the following format: “You have pulled in the database entry for <FIRSTNAME_VARIABLE> <LASTNAME_VARIABLE>, this individual is <AGE_VARIABLE> years old. Would you like to know more about them?”

 

This first example is showing the data as 3 separate variables and concatenating the strings together using the ‘+’ operator.

As you can see each time we switch from our static string to a variable we need to concatenate that with a “+” sign and we need to explicitly handle the ‘age’ variable as a string because it comes through as an integer. Looking at this you can see what it does but it is not very pretty, below is an example of the output you would see if you ran that function and fed it the variables first:’John’, last: ‘Smith’, age:50:

 

Now I would like to show you an example that produces the exact same result but when looking at the source code it is much more readable

As you can see we used .format() method on our string so that allowed us to embed a placeholder for our variables directly in the string without having to break up the string. The placeholder is the curly brackets ( {} ) and when using the .format() method it will place your variables inside of that placeholder.

You can see that I have also explicitly called my variables I wanted to put in the placeholder by using ‘0’, ‘1’, or ‘2’ which corresponds to the order i put my variables in .format() first, last, and age respectively.

Lastly one thing we do not need to worry about when using the format() method is handling integers because it does that automatically for us we do not need to wrap them in str()

Running this code and passing in the same variables you can see we get the same exact result as before.

 

Using the format method also provides us a very clean way of working with dictionaries lets say we are working with the following code:

Looking at our dictionary our key values are ‘first’, ‘last’, and ‘age’

Looking inside our print statement we can see that in the format method we only passed in 1 variable which is our entire dictionary so therefor we need to have an index of 0 inside of all of our curly bracket placeholders so it knows that we are still referencing our dictionary.

Lastly to extract the correct key values, to display in our placeholder we place standard brackets [] next to the 0 and enter the key value pair we wish to display, as you can see below after running this code we get the exact same output we saw in the above example where we worked with 3 separate variables.

 

The last example I will show using the format method will be working with strings, below is the code for this example:

Looking at this example it is very similar to working with a dictionary the only difference is in how we extract the information out of the data type.

Dictionaries use a key/value pair and when you want to get a specific value you call the key. To call the specific contents of a list you have to use its index number (from left to right starts at 0 and goes up from there). So we can see that the value ‘John’ in our list is the first entry so its index is 0 and looking at the print statement we have ‘Sohn’ being called in our first placeholder, ‘Smith’ being called in our second placeholder, and his age 50 being called in our third place holder.

When running this code we get the same output we have been getting so far in this tutorial

 

So which way is the correct way?

It is really up to personal preference but you will find the more you use string concatenation in your programs that using the ‘+’ operator will lead to more complex and error prone statements so I would argue it is best to use the format() method on a string as its easier to read and write especially when you start working with lists and dictionaries.

 

2 Comments

  1. I enjoyed your python blogs. The way you explain things is excellent.

    I think the blog on string formatting needs bringing up to date for f strings eg:

    name = ‘Kyle’
    print(f’Hi {name}’)

    Michael

1 Trackback / Pingback

  1. Python - List Comprehensions - Kyle Kowalczyk

Leave a Reply

Your email address will not be published.


*