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. →
sep
and end
// 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 can be used to format a value before you use it elsewhere (for example, before you print out to the user)
You can use format to ensure that you string has some number of characters in it.
'>20s'
and '<20s'
add spaces to the beginning and end of a string…formatted = format('hello', '>20s')
print(formatted)
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!
Specifying places after decimal (, means add comma, d means integer)
a = 20000
print(format(a, ',d'))
print(format(a, '>20,d'))
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)
There are a few other minor details with format →
format(1.2)
format(1.2, 's')
fill
, sign
, etc.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')