Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does = (equal) do in f-strings inside the expression curly brackets?

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=}') 
like image 616
ibarrond Avatar asked Jan 09 '20 10:01

ibarrond


People also ask

What is the use of f {} in Python?

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.

What happens if we use an expression inside an F-string?

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.

How do you put brackets in F-string?

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 }}.

What is F in front of string?

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 {} .


1 Answers

This is actually a brand-new feature as of Python 3.8.

Added an = specifier to f-strings. An f-string such as f'{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 >>> 
like image 152
juanpa.arrivillaga Avatar answered Sep 19 '22 10:09

juanpa.arrivillaga