Sub topic 3
Python Input, Output, and String Formatting
Assume you know variables, expressions, str, int, float, loops, and basic try/except. This chapter focuses on choosing a formatting method and moving text between a Python program and the outside world.
Quick debugging with `f"{x=}"`
An f-string with = displays both an expression and its value. It is useful for temporary debugging because the expression is labeled automatically.
name = "Ada"
score = 93.456
print(f"{name=}")
print(f"{score * 2 = }")The output includes name='Ada' and score * 2 = 186.912. Remove these prints after debugging or replace them with proper logging.
The `str.format()` method
str.format() is an older alternative to f-strings. It remains common in existing code and supports positional and named fields.
name = "Ada"
score = 93.456
print("{} scored {:.1f}".format(name, score))
print("{name} scored {score:.1f}".format(name=name, score=score))The format specification .1f displays one digit after the decimal point.
The `%` operator in legacy code
Printf-style formatting uses placeholders such as %s and %.1f.
print("%s scored %.1f" % ("Ada", 93.456))Prefer f-strings in new Python code. Recognize % formatting when maintaining older programs.
`string.Template` for user-supplied templates
Template supports simple $name placeholders without evaluating Python expressions. This makes it suitable when the template comes from outside the program.
from string import Template
template = Template("Hello, $name!")
print(template.safe_substitute(name="Ada"))Standard streams
A program normally reads from standard input (stdin) and writes normal results to standard output (stdout). Errors and warnings belong on standard error (stderr).
import sys
print("Result: 42", file=sys.stdout)
print("Warning: no data", file=sys.stderr)Reading and writing text files
Use with so Python closes the file even when an error occurs. Specify the encoding at the boundary.
with open("notes.txt", "w", encoding="utf-8") as file:
file.write("first line\n")
file.write("second line\n")
with open("notes.txt", encoding="utf-8") as file:
for line in file:
print(line.rstrip("\n"))Encodings and newline handling
An encoding maps characters to bytes. UTF-8 is the usual choice for new text files. A line ending is represented by a newline character. rstrip("\n") removes that character while preserving other whitespace.
Exercise
Which formatting style should new Python code usually use, and why?
Show answer
Use f-strings because they are readable and allow expressions and format specifications directly inside the string.