Skip to main content

Section 2.2 String formatting

Often your code will have some information that you want to present as text: printing a number with a certain number of significant figures, or including a bit of text into a longer bit of text. We can do all this and more with Python's string formatting methods.

String formatting has a long history going back to early programming languages. The developers of the Python language have tried to borrow the best ideas from other languages as Python has evolved over the last 30 years. The result is that Python has very powerful and convenient string formatting operations, but it also has quite a few older and less convenient ways to do the same things. Don't be surprised if you see some of these in existing code.

Subsection 2.2.1 Simple f-strings

Python "formatted string literals" (more colloquially known as f-strings) were introduced in Python 3.6. Unlike normal strings (which are fixed sequences of characters), f-strings can contain little bits of Python code which is run and inserted into the string as character data.

To create an f-string, simply prefix a normal string with the character f, like this: f"This is a formatted string!"

To use an f-string to format the value stored in a variable, include the name of that variable surrounded by a pair of curly braces ({ }):

Take a moment to run the code above. What happens if you remove the f before the string quotes? What happens if you change the string or the variable?

Subsection 2.2.2 Formatting numbers

F-strings are especially useful for formatting numbers in particular ways. By putting a colon after the variable followed by sequence of special characters (known as a format specifier, it is possible to control the number of significant figures, the display of a % sign, or even the visual alignment and spacing.

Experiment with the code above. What if you use e, g, or % in place of the f? What if you change the 3 to another number?

You can also insert strings into f-strings, and include multiple replacement fields:

These examples have just scratched the surface of what is possible with format strings. You can read more, including all of the possible string format specifiers, in the official Python documentation 1 .

docs.python.org/3/library/string.html#formatspec