f-strings Containing Python Code
Learn how to use Python f-strings and explore format specifiers for versatile string formatting.
We'll cover the following
Overview
We aren’t restricted to interpolating the values of simple string variables into an f-string template. Any primitives, such as integers or floats, can be formatted. More interestingly, complex objects, including lists, tuples, dictionaries, and arbitrary objects, can be used, and we can access indexes and variables or call functions on those objects from within the format
string.
Example
For example, if our email message had grouped the From
and To
email addresses into a tuple and placed the subject and message in a dictionary, for some reason (perhaps because that’s the input required for an existing send_mail
function we want to use), we can format it like this:
Get hands-on with 1400+ tech skills courses.