String Formatting in Python 3

This post presents a series of examples of string formatting in Python 3 and Python 3.6+.

Format Strings In Python 3

Strings in Python 3 have a method format that constructs a new string with dynamic values. Parameters can be passed to format as arguments or as keyword arguments.

phrase = "world"

# Argument formatting
"Hello, {}".format(phrase)
=> Hello, world

# Keyword argument formatting
"Hello, {name}".format(name=phrase)
=> Hello, world

Literal String Interpolation In Python 3.6+

Python 3.6 introduced literal string formatting by using the f or F prefix. By using the f or F prefix, variables in scope are inserted directly into the string without the need to call format.

phrase = "world"

f'Hello, {phrase}'
=> Hello, world

# " and F may also be used
F"Hello, {phrase}"
=> Hello, world

Custom Strings In Python

That's it! With the format in Python 3 and literal string interpolation in Python 3.6+ you can create custom strings with dynamic values.