How do f-strings work and what formatting tricks are useful in reports?
BeginnerConceptLanguage essentials & functions
Answer
f-strings evaluate expressions inline: f"{name} has {count} findings". Useful format specs:
f"{cpu:.1f}%" # 3.1%
f"{size_bytes:,}" # 1,234,567
f"{name:<20}|" # left-align in 20 chars
f"{ratio:.0%}" # 87%
f"{value=}" # value=42 (debugging, 3.8+)
Do not use f-strings to build SQL, shell commands or log messages. For logging, pass arguments (log.info("found %d", n)) so formatting is lazy and log aggregators can group messages.
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?Beginner