Formatting Output

Formatting With Print (Review)

How can we format output with print (that is, control what gets printed out between separate arguments, and what gets printed out after the actual value)?

We can use special arguments, called keyword arguments, to control output with print. sep="separator" and end="ending".

Let's check out some examples in the next slide.

Formatting With Print Examples

// instead of using space to separate arguments, use comma!
print("foo", "bar", "baz", sep=", ")

// use a + instead of a newline at the end!
print("foo", "bar", "baz", end="+")

// you can combine both sep and end
print("foo", "bar", "baz", sep=", ", end="+")

The format() Function

The format() function can be used to format a value before you use it elsewhere (for example, before you print out to the user)

Padding Strings

You can use format to ensure that you string has some number of characters in it.

formatted = format('hello', '>20s')
print(formatted)

Examples of Formatting Floats

Specifying places after decimal (. means decimal, number is the number of spaces, f means floating point format)

a = 1.333333
b = format (a, '.2f') # format as a float, 1.33
c = format (a, '.3f') # format as a float, 1.333
d = format (a, ',.5f') # add a comma separator
e = format (a, '>20,.2f') # pad it too!

Examples of Formatting Integers

Specifying places after decimal (, means add comma, d means integer)

a = 20000
print(format(a, ',d'))
print(format(a, '>20,d'))

The Formal Specification

Ok… so if you want to know how format really works:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
fill        ::=  <any character>
align       ::=  "<" | ">" | "=" | "^"
sign        ::=  "+" | "-" | " "
width       ::=  integer
precision   ::=  integer
type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | 
                 "G" | "n" | "o" | "s" | "x" | "X" | "%"

(taken from the official documentation)

Additional Notes

There are a few other minor details with format

Let's Try This…

What format string should we use to format the number 1000.32 so that it gives back a stirng composed of 20 characters:

'---------1,000.32000'

format(1000.32, '->20,.5f')