Format strings (f-strings) in Python

Python Methods and Functions

Formatted string literals are also known as f-strings or format strings.

Formatted string literals are string literals prefixed with f or F .

  animal = `cat` 
age = 7
f` I have {animal}. Him {age + 1} .` # I have a cat. He`s 8.

def print_me (one, two):
print (f`Here you are {one}, here you are {two} .`)

Such lines may contain replacement markers (expressions in curly braces - {} ). While regular literals are constants, the values ​​of formatted strings are calculated during program execution.

The portion of the string outside the curly braces remains unchanged (except for the double curly braces {{ or }} , which are replaced with single ones). A single open parenthesis { signals the start of a replacement marker ( Python expressions ), which may be followed by a conversion pointer (starting with an exclamation point character ! ), as well as a format indicator (begins with a colon : ). The marker ends with a curly closing brace } .

> ) will result in an exception SyntaxError .

General view of the marker: {(expression) [! transform] [: format]} .

Markers can include other markers.

Expressions inside parentheses are treated like regular expressions with a few caveats:
  • Empty expressions are not allowed;
  • Lambda expressions must be surrounded by parentheses;
  • Line breaks are allowed (for example , in triple-quoted literals), but comments are not supported;
  • Each expression is evaluated in the same context as the format string, from left to right.

Next conversion uses mini formatting language using the format () . Format settings are passed to the __format __ () method (if not specified, an empty string is passed). 

  animal = `cat` 
f" {animal: & gt; 6} "#` cat`

After that, the marker in the line is replaced with the formatted result of evaluating the expression.


Format strings can be glued together, but the markers must not belong to different literals.


If a transformation is requested, it will be performed on the result of evaluating the expression just before formatting. 

! r Use < a href = "/ references / named / repr /"> repr () .
! s Use str () .
! A Use ascii () .

 < code class = "python"> animal = `cat` 
f`I have a {animal! r} .` # I have a` cat`.
f`I have a {repr (animal)}. `# I have a` cat`.

# Nested markers:
width = 10
precision = 4
value = decimal.Decimal (`12.34567`)
f`result : {value: {width}. {precision}} `# result: 12.35

Simplified for debugging
Since + py3.8 you can use the form f` {my_var =} ` to print the name of a variable and its current value.

  my_var = `cat` 
print (f` {my_var =}`) # my_ var = `cat`
# It is possible to pad the string to the specified length:
print (f` {my_var.upper () =: a ^ 7}`) # my_var = `aaCATaa`
print (f `{my_var.upper () =: b & gt; 7} `) # my_var =` bbbbCAT`

Get Solution for free from DataCamp guru