For loop in f-string python

Both ternaries ("if expressions") and comprehensions ("for expressions") are allowed inside f-strings. However, they must be part of expressions that evaluate to strings. For example, key: value is a dict pair, and f"{key}: {value}" is required to produce a string.

>>> dct = {'a': 1, 'b': 2}
>>> newline = "\n"  # \escapes are not allowed inside f-strings
>>> print(f'{newline.join(f"{key}: {value}" for key, value in dct.items())}')
a: 1
b: 2

Note that if the entire f-string is a single format expression, it is simpler to just evaluate the expression directly.

>>> print("\n".join(f"{key}: {value}" for key, value in dct.items())))
a: 1
b: 2

Expressions inside format strings still follow their regular semantics. For example, a ternary may test whether an existing name is true. It will fail if the name is not defined.

>>> c, name = "Hello", ""
>>> f'{c} {name if name else "unknown"}'
'Hello unknown'
>>> del name
>>> f'{c} {name if name else "unknown"}'
NameError: name 'name' is not defined

Dive into the string formatting technique in Python

Photo by Bruce Tang on Unsplash

The f-string, which was introduced by Python 3.6, is a simple and different string formatting technique to express Python strings elegantly.

Unless you are still using the old Python versions, the f-string should definitely be your preference when formatting strings. Because it can satisfy all your requirements by a minima syntax, and even run expressions in strings.

This article will dive into this technique from elementary to profound by 7 levels. After understanding them all, you probably will become a string formatting master.

1. Display Values From Variables Easily

There are only two things you need to do to use f-strings:

  • Add an f before the string.
  • Use the {variable_name} to interpolate a variable’s value in the string.
name = 'Yang'
title = 'full stack hacker'
print(f'{name} is a {title}.')
# Yang is a full stack hacker.

As shown above, with the help of the f-string mechanism, we can write simple and less code to display more in a string. It echoes the zen of Python perfectly.

“Simple is better than complex.” — The Zen of Python

2. Use Format Specifications To Print Values as You Like

Sometimes, just displaying an original value may not satisfy our needs. However, to modify the original variable directly is usually not a good idea, cause the variable may be used elsewhere.

No worries at all, Python f-strings support the “format specification mini-language”, which gives us abilities to format values in f-strings as we like.

Format specifications in f-strings

The above example just shows the tip of the iceberg. For a full list of the format specifications’ syntax, the corresponding official document is your best friend.

3. Print Special Characters Properly

Can we print the '', {} or other special characters by an f-string?

Yes, of course. But the syntax is a little tricky. Let’s have a look.

3.1 Print quotations marks

As we know, the backslash (\) is the commonly used escape character to invoke an alternative interpretation on its following character. For f-strings, we need to pay attention to one rule:

The backslash doesn’t work inside an f-string expression.

Print quotations marks by f-strings

As shown above, if we would like to add quotation marks for the name, we must add them outside the braces.

3.2 Print braces

The way to print braces by f-strings is different (even a little bug-prone). We can’t use backslash this time.

Print braces by f-strings

As the above example shows, whether the name is treated as a substring or a variable is depended on the number of braces around it. Here is the bug-prone if you don’t know this weird mechanism.

3.3 Print a backslash

Print a backslash is simple: just using double backslashes to print one. And don’t add them inside the f-string expressions.

Print backslashes by an f-string

4. Apply Dictionary Values Carefully

It’s also bug-prone to apply a dictionary’s values into an f-string. Because we must use different quotations to the dictionary key and f-string.

Use different quotations for keys and f-strings

As shown above, if we use the same single or double quotations for both keys and f-strings. Python will be confused about our code. 😃

5. Handle Multiline F-Strings Correctly

To make our code more readable, it’s necessary to write a long string by multi lines. But if it’s an f-string, don’t forget to add the f before each line:

Write an f-string by multi lines

6. Display Date and Time Like a Guru

If we need to print dates or time, the f-string will show us how convenient it is again:

Print date as we like by f-strings

Like the above example, with the help of the f-strings, we can print dates or time by any format we like.

If you aren’t familiar the date handling in Python yet, this article will give you a hand: 5 Levels of Handling Date and Time in Python.

7. Evaluate Expressions Inside F-Strings

When I first knew the f-string mechanism, I can’t believe this: we can run a Python expression inside an f-string. If it’s true, is it still a string?

I read PEP 498 carefully and finally understand it:

F-strings provide a way to embed expressions inside string literals. It should be noted that an f-string is really an expression evaluated at run time, not a constant value.

So, an f-string is not the same as a normal string. This feature gives it more power.

For example, we can run a function inside it.

Run a function inside an f-string

Conclusion

The f-string mechanism in Python is a great string formatting technique which shows how elegant Python is. It’s powerful because it’s not a normal string but an expression evaluated at run time. And for a few special cases, it has special rules and we need to use it carefully.

Thanks for reading. If you like it, please follow me to enjoy more great articles.

More interesting Python posts for you:

More content at plainenglish.io

What are F strings for in Python?

F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces.

What is %s and %D in Python?

%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values. For example (for python 3) print ('%s is %d years old' % ('Joe', 42)) Would output Joe is 42 years old.

How do you escape an F

Python f-string escaping characters To escape a curly bracket, we double the character. A single quote is escaped with a backslash character.

How do you use backslash in Python F

Use the Python backslash ( \ ) to escape other special characters in a string. F-strings cannot contains the backslash a part of expression inside the curly braces {} . Raw strings treat the backslash (\) as a literal character.