The usage of {} in Python f-strings is well known to execute pieces of code and give the result in string
format (some tutorials here). However, what does the '=' at the end of the expression mean?
log_file = open("log_aug_19.txt", "w") console_error = '...stuff...' # the real code generates it with regex log_file.write(f'{console_error=}')
Python f-string is the newest Python syntax to do string formatting. It is available since Python 3.6. Python f-strings provide a faster, more readable, more concise, and less error prone way of formatting strings in Python. The f-strings have the f prefix and use {} brackets to evaluate values.
f-string allows us to evaluate expressions inside the string. Just put the expression inside { } to evaluate. f-string evaluates it at runtime of the program. It's an excellent feature which saves you time and code.
Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.
The f means Formatted string literals and it's new in Python 3.6 . A formatted string literal or f-string is a string literal that is prefixed with 'f' or 'F' . These strings may contain replacement fields, which are expressions delimited by curly braces {} .
This is actually a brand-new feature as of Python 3.8.
Added an
=
specifier to f-strings. An f-string such asf'{expr=}'
will expand to the text of the expression, an equal sign, then the representation of the evaluated expression.
Essentially, it facilitates the frequent use-case of print-debugging, so, whereas we would normally have to write:
f"some_var={some_var}"
we can now write:
f"{some_var=}"
So, as a demonstration, using a shiny-new Python 3.8.0 REPL:
>>> print(f"{foo=}") foo=42 >>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With