Python3 f-Strings and string formatting syntax

Python3 f-Strings and string formatting syntax

As of Python 3.6, f-strings are a great new way to format string. Not only are they more readable, more concise, and less prone to error than other ways of formatting, but they are also faster!

f-string Magic

Simple Syntax:

The syntax is similar to the one you used with str.format() but less verbose. Look at how easily readable this is:

>>> name = "Eric"
>>> age = 74
>>> f"Hello, {name}. You are {age}."
'Hello, Eric. You are 74.'

It would also be valid to use a capital letter F:

>>> F"Hello, {name}. You are {age}."
'Hello, Eric. You are 74.'

Quotation Marks

Quotation Marks
You can use various types of quotation marks inside the expressions. Just make sure you are not using the same type of quotation mark on the outside of the f-string as you are using in the expression.

This code will work:

>>> f"{'Eric Idle'}"
'Eric Idle'

This code will also work:

>>> f'{"Eric Idle"}'
'Eric Idle'

You can also use triple quotes:

>>> f"""Eric Idle"""
'Eric Idle'

>>> f'''Eric Idle'''
'Eric Idle'

Multiline f-strings

You can have multiline strings:

name = "Eric"
profession = "comedian"
affiliation = "Monty Python"
message = (
    f"Hi {name}. "
    f"You are a {profession}. "
    f"You were in {affiliation}."

#'Hi Eric. You are a comedian. You were in Monty Python.'

But remember that you need to place an f in front of each line of a multiline string. The following code won’t work:

message = (
    f"Hi {name}. "
    "You are a {profession}. "
    "You were in {affiliation}."

#'Hi Eric. You are a {profession}. You were in {affiliation}.'

But this is what will happen if you use """:

name = "Eric"
profession = "comedian"
affiliation = "Monty Python"

message = f"""
    Hi {name}. 
    You are a {profession}. 
    You were in {affiliation}.


#'\n    Hi Eric.\n    You are a comedian.\n    You were in Monty Python.\n'

Arbitrary Expressions

Because f-strings are evaluated at runtime, you can put any and all valid Python expressions in them. This allows you to do some nifty things.

You could do something pretty straightforward, like this:

f"{2 * 37}"

But you could also call functions. Here’s an example:

def to_lowercase(input):
    return input.lower()

name = "Eric Idle"
f"{to_lowercase(name)} is funny."

#'eric idle is funny.'


In order to make a brace appear in your string, you must use double braces:

>>> f"{{74}}"

Note that using triple braces will result in there being only single braces in your string:

>>> f"{{{74}}}"

However, you can get more braces to show if you use more than triple braces:

>>> f"{{{{74}}}}"

'f-strings' may be combined with 'r' to produce raw f-string which can be used inside regex or similar functions. 'f-strings' may not be combined with 'u', this is because all Python3.6+ strings are Unicode by default now. This means, you can write fstrings in Hindi, Chinese, French, Korean and any language covered by Unicode.

Simplified Alignment and Spacing

Have you ever tried creating a table such as that for logging or visualization? Arranging the elements becomes a nightmare with several \t tab characters flying around.

This is much easier with Python f-strings using the colon : operator, followed by a an alignment operator and field width value.

Option Meaning
< Forces the field to be left-aligned within the available space (this is the default for most objects).
> Forces the field to be right-aligned within the available space (this is the default for numbers).
= Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types. It becomes the default when ‘0’ immediately precedes the field width.
^ Forces the field to be centered within the available space.
correct = 'correct'
phonetic_correct = 'phonetic_correct'
typo = 'typo'
phonetic_typo = 'phonetic_typo'
phonetic_distance = 'phonetic_distance'

print(f'No Spacing:')
# No Spacing:
# correct|phonetic_correct|typo|phonetic_typo|phonetic_distance|

print(f'Right Aligned:')
# Right Aligned:
# ___correct|____phonetic_correct|______typo|_______phonetic_typo|___phonetic_distance|

print(f'Left Aligned:')
# Left Aligned:
# correct___|phonetic_correct____|typo______|phonetic_typo_______|phonetic_distance___|

print(f'Centre Aligned:')
# Centre Aligned:
# _correct__|__phonetic_correct__|___typo___|___phonetic_typo____|_phonetic_distance__|

# correct  |  phonetic_correct  |   typo   |   phonetic_typo    | phonetic_distance  |

#| correct  |  phonetic_correct  |   typo   |   phonetic_typo    | phonetic_distance  |