String Formatting

In this lesson we will cover different ways to format strings in Python.

What if we wanted to create a function that greets a user when the function is called. Until now, we would have to manually concatenate each string using the + sign. This was ok for small strings, but as messages grow larger, it becomes a real pain.

Fortunately, Python gives us an easy way to automatically input information into a string, using a process known as f strings.

f Strings

Note: f strings only work in python versions 3.6 or greater

Let’s create a simple greeting function:

def greet(name):
    print("Hello " + name )

greet("John") # Prints Hello John

This works, but lets convert this program to use f strings. To use an f string, simply put a lower-case, or upper-case, f before the first quotation mark, then place all the parameters you want within a set of curly braces: {}.

def greet(name):
    print(f"Hello {name}")

greet("John") # Prints Hello John

Addendum

Python f strings also allow for evaluation to happen within the curly braces, so we could write an expression and have it automatically entered into the string.

print(f"2 + 6 = {2+6}")
# Prints "2 + 6 = 8"