String formatting in Python

One of the most confusing things in Python for the new programmer is string formatting. Not because it's difficult in Python, but because the way to do it has changed many times over the years.

Below is a reverse timeline of ways to do string formatting in Python. It is recommended that you follow the first method of formatting.

All the code snippets ask the user for their name (e.g. "Jose"), and then print out a greeting ("Hello, Jose!").

f-strings

The most modern method for string formatting is f-strings, new in Python3.6. This is the way I'd recommend doing string formatting!

user_name = input('Enter your name: ')  # Ask user for their name
greeting = f'Hello, {user_name}!'  # Construct a greeting phrase
print(greeting)

The f-string will replace whatever is inside the curly braces by the variable in the scope. Thus {user_name} in the variable would be replaced by the value of the user_name variable.

.format()

The .format() method is a great way to do string formatting, but it can almost always be replaced by f-strings.

Here's an example of this:

user_name = input('Enter your name: ')
greeting = 'Hello, {}!'.format(user_name)
print(greeting)

In the .format() method, we replace the {} inside the string for the value inside the brackets.

Templates

Templates allow you to create re-usable strings where special placeholders can be replaced by values. They are much slower than any other form of formatting, and provide few or no benefits over the above two.

Here's an example:

from string import Template
user_name = input('Enter your name: ')
greeting_template = Template('Hello, $who!')
greeting = s.substitute(who=user_name)
print(greeting)

String concatenation

String concatenation is the simplest and oldest form of string formatting in Python. It's useful when you have very simple strings, with little formatting.

Here's an example:

user_name = input('Enter your name: ')
greeting = 'Hello, ' + user_name + '!'
print(greeting)

However, it's easy to create unexpected errors in your Python code when joining things together that are not strings, as we see from the examples below:

age = 30
greeting = 'You are ' + age + ' years old.'  # This raises an error!
print(greeting)

This was a quick, short overview of the existing ways of doing string formatting in Python. There's many different ways!

Many different tutorials may suggest different ways of doing string formatting because they may have been written at different times over Python's life. My recommendation: stick to f-strings if on Python3.6, and to the .format method if on Python3.5 or earlier.