StringsChapter 20 of 114
String Formatting
format(), the older % style, and how to line text up in columns.
Why this chapter exists
f-strings are what you should write. You still need to read the two older styles, because they are everywhere in existing code, and one of them is still the right tool when the template is not a literal.
str.format()
Placeholders are empty braces filled from the arguments:
template = "{} is {}"
print(template.format("Ada", 36))Output
Ada is 36
The advantage over an f-string: the template can be a variable, decided at runtime or loaded from a file. An f-string is interpolated where it is written, so it cannot do that.
Placeholders can be numbered or named, which makes long templates readable and lets you repeat a value:
print("{0} scored {1}, so {0} wins".format("Ada", 9))
print("{name} is {age}".format(name="Ada", age=36))Output
Ada scored 9, so Ada wins Ada is 36
The format spec after a colon is identical to the f-string one:
print("{:,.2f}".format(1234.5678))Output
1,234.57
The % style
The oldest form, borrowed from C. You will meet it in old code and in logging:
print("%s is %d" % ("Ada", 36))
print("%.2f" % 3.14159)Output
Ada is 36 3.14
%s takes anything, %d an integer, %f a float. It is positional and easy to get wrong — one value needs a trailing comma to be a tuple — so do not start new code with it.
Lining things up
Width and alignment turn a loop into a table:
rows = [("Ada", 36), ("Grace", 45), ("Katherine", 101)]
for name, age in rows:
print(f"{name:<12}{age:>4}")Output
Ada 36 Grace 45 Katherine 101
Pick a fill character by putting it before the alignment:
print(f"{'Total':.<20}{42:.>6}")Output
Total...................42
Centring and truncating
print(f"|{'title':^20}|")
print(f"{'a very long value':.10}")Output
| title | a very lon
A bare number after the dot truncates a string, which is handy for keeping columns from blowing out.
Which to use
- f-string for almost everything
str.format()when the template is not written where it is used%when the surrounding code already uses it, and in logging calls
Test yourself
2 questionsWhen is str.format() a better choice than an f-string?
Show the answer
When the template is a variable rather than written where it is used — An f-string is interpolated where it is written, so it cannot take a template loaded from elsewhere.
What does f"{name:<12}" do?
Show the answer
Pads name on the right to at least 12 characters — The < aligns left, so the padding goes on the right. Use > to right-align.
Escape Characters
Backslashes for newlines, tabs and quotes, and the raw strings that switch them off.