Salvatore Lopiparo

Senior Software Engineer

Super Simple Python – Basic String Formatting

String formatting is the process of making your strings flexible and pretty.

Let’s say we want to print out a bunch of information about some numbers.

----------------
1. Number: 2
2. Odd?: False
3. x*2: 4
4. Factorial: 2

Now if we were to try to create this string by adding all the parts together, it would be a giant mess – something like the following. (We’re using the math module in this code bit, so first run a import math to make it available.)

import math

for number in range(5):
    output_string = "----------------n"
    output_string += "1. Number: " + str(number) + "n"
    output_string += "2. False?: " + str(True if number % 2 else False) + "n"
    output_string += "3. x*2: " + str(number * 2) + "n"
    output_string += "4. Factorial: " + str(math.factorial(number)) + "n"

    print(output_string)

It can be difficult to sort out the difference between the code and the string using this method. Remember that being able to read and understand your code in the future is one of the most important aspects of programming!

There is, thankfully, a much cleaner way to do this. We can build a template string with keys to identify where we want variables to go.

template_string = """----------------
1. Number: {number}
2. Odd?: {is_odd}
3. x*2: {times_two}
4. Factorial: {factorial}"""

Now that we have a template string with keys like {number} and {is_odd}, we can use the format function to add our variables to the keys. This will, for example, replace the key {number} with the argument number that we pass to the format function.

import math

for number in range(5):
    is_odd = True if number % 2 else False
    times_two = number * 2
    factorial = math.factorial(number)

    formatted_string = template_string.format(  # Replaces keys with keyword arguments
            number=number,
            is_odd=is_odd,
            times_two=times_two,
            factorial=factorial)
    print(formatted_string)

This easier-to-read bit of code will give us a very nicely structured print statement.

You can also use string.format() with positional arguments instead of keyword arguments like so:

>>> greeting = "It's {0}, {1}! It's {0}!".format(  # Replaces keys with arguments
...     "Tuesday", "James")
>>> print(greeting)
It's Tuesday, James! It's Tuesday!

The keys {0} and {1} indicate the arguments passed to the format method. The first argument "Tuesday" will replace anywhere with a {0}, and the second argument "James" replaces {1}.

The string.format() method is the current prefered method for string formatting. With a bit of practice, manipulating strings will become second nature! There are even more interesting things you can do with string formatting, which we’ll look at in another episode!

Leave a Reply