Motivation

Was working on a HackerRank challenge and I found myself wondering what the cleanest solution should look like. F-strings!

Example problem

Given the list of scores: [10, 20, 30], give the average value correct to 2 decimal places.

The solution

This solution should work for any list containing integers regardless of length.

1
2
3
4
scores = [10, 20, 30]

# notice usage of f-strings
print(f"{sum(scores)/len(scores):.2f}")

Neat, right?

References

  1. Python 3's f-Strings: An Improved String Formatting Syntax (Guide)
  2. Python 3 Float Decimal Points/Precision