Skip to content

← Pattern Matching, f-Strings and Newer Syntax step 1 of 23

Easy Primitives

Show Values with repr and str in f-Strings

When you debug, you often print a variable next to its name. Put = after the expression, and the f-string writes the name for you:

total = 19.99
label = "it's"
print(f"{total=}")      # total=19.99
print(f"{label=}")      # label="it's"
print(f"{label=!s}")    # label=it's
print(f"{total=:.1f}")  # total=20.0

The = form shows the value with repr, which is why label keeps its quotes. repr shows quotes and escapes, so you can spot an empty string or a stray newline. str gives the plain text a user should read. A conversion picks one of the two. !r means repr and !s means str. If you add a format spec, the part after the colon, Python formats the value with that spec instead.

= copies the expression exactly as you typed it. With name = "count", f"{name=}" gives name='count', not count=.... In this exercise the names arrive as data, so you build each name=value entry yourself and choose the conversion.

What to write

Fill in three functions:

  • debug_repr(**values): format each entry as f"{name}={value!r}", and join the entries with ", ".
  • display(**values): do the same with !s instead of !r.
  • solve(pairs): build a dictionary from the pairs, pass it to both functions with **, and join the two results with one newline.

With [["n", 42], ["label", "it's"]], solve returns:

n=42, label="it's"
n=42, label=it's

Follow these rules:

  • Each pair holds exactly two items, a name and a value. Make the key with str(name). A name can arrive as a number, and ** accepts only string keys.
  • Keep the entries in the order of the pairs. A dictionary and ** both keep insertion order.
  • If two names give the same key, such as 1 and "1", the later value replaces the earlier one. The entry stays where the first one was.
  • Leave the input pairs unchanged.

Edge cases

  • An empty list of pairs gives exactly "\n". Both lines are empty.
  • An empty string shows as '' in the debug line and as nothing after the = in the display line.
  • A newline inside a value shows as \n in the debug line. str keeps the real newline, so the result can take up more than two lines.