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!

Super Simple Python #14 – Advanced Strings and Formatting

We dealt with some simple string stuff early on, but it was fairly limited in what you can do. In this lesson, I’ll teach you all the fancy stuff they don’t teach you in grade school! (Actually, I’m not sure they teach any of this stuff in grade school.)

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

Special Characters

There are two special white-space characters that are useful to know and are used commonly: newline, \n, and tab, \t. They are known as white-space characters because they don’t actually draw a character. They are invisible characters, similar to a space from the space bar (as opposed to a space martini from the Space Bar).

The tab character \t adds a large space as if you hit the “Tab” key on the keyboard. It can be useful when you want to do some simple formatting.

>>> balloons = {'red': 12, 'blue': 8, 'green': 14}
>>> for color in balloons:
...     print(color + '\t\t' + str(balloons[color]))
...
red     12
blue        8
green       14

The newline character \n is an invisible character that means “start writing on the next line”. It is used when you have a long string that would look nicer on two lines.

>>> for color in balloons:
...     print("The number of " + color + ' balloons is on the next line!\n\t' + str(balloons[color]))
...
The number of red balloons is on the next line!
    12
The number of blue balloons is on the next line!
    8
The number of green balloons is on the next line!
    14

Sometimes you may want to have an actual backslash before the letter ‘n’. In this case, you must escape the backslash: \\n. A single backslash says “THE NEXT CHARACTER IS SPECIAL!” A double backslash says “THE NEXT CHARACTER IS NOT SPECIAL, I AM!”

>>> print('before\nafter')
before
after
>>> print('before\\nafter')
before\nafter

Raw Strings

There are a couple special string types that are not commonly used, but one is worth mentioning. The raw string type takes any special characters and escapes them automatically. You can write a raw string by putting an r directly in front of the string: r'my string'. Note in the following example that we use \n for \name.txt, but because we’re using raw it escapes the character for us.

>>> # This will auto-escape! The path will be complete!
>>> raw_file_path = r"C:\some\path\name.txt"
>>> raw_file_path
'C:\\some\\path\\name.txt'
>>> print(raw_file_path)
C:\some\path\name.txt
>>>
>>> # This will NOT escape! The path will be broken!
>>> non_raw_path = "C:\some\path\name.txt"
>>> non_raw_path
'C:\\some\\path\name.txt'
>>> print(non_raw_path)
C:\some\path
ame.txt