CMSC 201 - Lec18 - String Formatting
CMSC 201 - Lec18 - String Formatting
All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Last Class We Covered
• Recursion
– Recursion
• Recursion
• Fibonacci Sequences
• Recursion vs Iteration
2 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Any Questions from Last Time?
3 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Today’s Objectives
• To understand the purpose of string formatting
• To examine examples of string formatting
– To learn the different type specifiers
• To briefly discuss tuples
• To learn the details of string formatting
– Alignment
– Fill characters
4 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Basic String Formatting
5 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Common Use Cases
• How can we…
– Print a float without the decimals?
Accomplishing
print( int(myFloat) ) either of these
• But what if we wanted it rounded up? would require a
lot of extra work
– Line information up into columns?
print(column1, "\t", column2)
• But what about when one thing is very long/short?
6 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
String Formatting Possibilities
• Align text left, right, or center
7 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Anatomy of String Formatting
string that is being printed
print("hello {:*^9}".format("world"))
name of the
details of how the method
formatting will be applied
information that
will be formatted
• This would output:
hello **world**
8 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Type Specifiers
• String formatting often needs to know the
exact type of the data it’s formatting
– Or at least how it should be handled
9 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Integer Formatting Examples
>>> classNum = 201
>>> print("Welcome to {}!".format(classNum))
Welcome to 201!
If nothing is specified, no
formatting is applied
{ : 0 # d }
(In actual code,
Must always contain
don’t leave
the opening and closing
spaces between
curly braces, the colon,
anything.)
and the 'd' specifier.
11 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Float Formatting Examples
>>> midAvg = 142.86581
>>> print("The midterm average was {:2.0}".format(midAvg))
The midterm average was 1e+02
>>> print("The midterm average was {:2.0f}".format(midAvg))
The midterm average was 143
{ : 0 # . # f }_
(In actual code,
don’t leave Maximum number of
spaces between digits after decimal Will automatically
round, or will pad
anything.) with trailing zeros
14 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
String Formatting Examples
>>> best = "dogs"
>>> print("{} are the best animal".format(best))
dogs are the best animal
If nothing is specified, no
formatting is applied
>>> print("{:7s} are the best animal".format(best))
dogs are the best animal
Specifying “too many”
characters will add padding
>>> print("{:07s} are the best animal".format(best))
Traceback (most recent call last):
File "<stdin>", line 1, in <module> Doesn’t work with strings!
ValueError: '=' alignment not allowed (At least, not by itself.)
in string format specifier
15 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
String Formatting “Rules”
Minimum number of
characters displayed
{ : # s }
(In actual code,
don’t leave
spaces between
anything.)
16 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
String Formatting on
Multiple Items
17 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Applying to Multiple Items
• To apply string formatting to more than one
variable (or literal) within a string, simply use
– Two sets of {} braces with formatting info
– Two items in the parentheses at the end
>>> major = "CMSC"
>>> print("Ready for {:10s} {:04d}?".format(major, 202))
Ready for CMSC 0202?
20 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Getting Fancy
21 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Alignment Options
• Can left, right, or center align with formatting:
– Left < In Python 3, left is the
– Right > default for strings, and right
– Center ^ is default for numbers
22 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Padding Characters
• Default padding for strings is spaces
• Default padding for numbers is zeros
23 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Using Variables
• You can use variables for any of the values in
the formatting (size, padding character, etc.)
– Must use concatenation to put together
>>> c = "~"
>>> print( ("why not {:" + c + "^7d}?").format(2))
why not ~~~2~~~?
24 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
“Rules” for Fancy Stuff
Padding character
comes right after : Must have an alignment if
you have padding character
{ : X < otherStuff }
(In actual code,
don’t leave
spaces between All the other formatting
anything.) info comes after these two
25 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Example Usage of Formatting
kennel = ["Akita", "Boxer", "Collie", "Dalmatian", "Eurasier"]
for i in range(len(kennel)):
print("There is a {:>10s} in pen".format(kennel[i]), i)
26 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
String Formatting Exercises
27 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Formatting Exercises
print("My dog {}.".format("Hrabowski"))
• What formatting is needed for each outcome?
My dog Hrabowski.
My dog Hrabowski .
My dog _Hrabowski_.
My dog _Hrabowski__.
28 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Formatting Exercises
print("My dog {}.".format("Hrabowski"))
• What formatting is needed for each outcome?
My dog Hrabowski.
Left aligned is default,
{:>11s} so specifying isn’t
My dog Hrabowski . technically necessary.
{:<11s} {:11s}
My dog _Hrabowski_.
{:_^11s} If perfect centering isn’t
My dog _Hrabowski__. possible, the extra
{:_^12s} character goes on the right.
29 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
More Formatting Exercises
PI = 3.1415926535897932384626433
print("Isn't {} great?".format(PI))
• What formatting is needed for each outcome?
Isn't 3.141593 great?
30 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
More Formatting Exercises
PI = 3.1415926535897932384626433
print("Isn't {} great?".format(PI))
• What formatting is needed for each outcome?
Isn't 3.141593 great? The default is also
{:.6f} 6 decimal values.
Isn't 3.141593 great? {:f}
{:10f}
Isn't 003.14 great? Padding numbers
{:06.2f} with zeros doesn’t
require an alignment.
31 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Even More Formatting Exercises
• What formatting would be generated here?
print("{:1.3f}".format(PI))
print("{:*^10s} is great!".format("Neary"))
32 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Even More Formatting Exercises
• What formatting would be generated here?
print("{:1.3f}".format(PI))
3.142
print("{:*^10s} is great!".format("Neary"))
**Neary*** is great!
print("It's over {:0<4d}!".format(9))
It's over 9000!
print("{:>7s} {:^^7s}".format("Hello", "world"))
Hello ^world^
33 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
• Sophie Wilson
– Designed the Acorn
Micro-Computer in 1979
• Wrote BBC BASIC, the
programming language
– Designed the instruction
set of the ARM processor
• Most widely-used
architecture in modern
smartphones
34 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Announcements
• Project 2 is due Friday 11/9 at 8:59:59PM
35 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu
Image Sources
• Sophie Wilson (adapted from)
– https://www.flickr.com/photos/101251639@N02/9669448671
36 All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted www.umbc.edu