Formatting Strings
We'll cover the following...
Let’s take another look at humansize.py
:
SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], #①1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}def approximate_size(size, a_kilobyte_is_1024_bytes=True):'''Convert a file size to human-readable form. #②Keyword arguments:size -- file size in bytesa_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024if False, use multiples of 1000Returns: string''' #③if size < 0:raise ValueError('number must be non-negative') #④multiple = 1024 if a_kilobyte_is_1024_bytes else 1000for suffix in SUFFIXES[multiple]:size /= multipleif size < multiple:return '{0:.1f} {1}'.format(size, suffix) #⑤raise ValueError('number too large')
① 'KB'
, 'MB'
, 'GB'
… those are each strings.
② Function docstrings are strings. This docstring spans multiple lines, so it uses three-in-a-row quotes to start and end the string.
③ These three-in-a-row quotes end the docstring.
④ There’s another string, being passed to the exception as a human-readable error message.
⑤ There’s a… whoa, what the heck is that?
Strings can be defined with either single or double quotes.
Python 3 supports formatting values into strings. Although this can include very complicated expressions, the most basic usage is to insert a value into a string with a single placeholder.
username = 'mark'password = 'PapayaWhip' #①print ("{0}'s password is {1}".format(username, password)) #②#"mark's password is PapayaWhip"
① No, my password is not really PapayaWhip
.
② There’s a lot going on here. First, that’s a method call on a string literal. Strings are objects, and objects have methods. Second, the whole expression evaluates to a string. Third, {0}
and {1}
are replacement fields, which are replaced by the arguments passed to the format()
method.
Compound field names
The previous example shows the simplest case, where the replacement fields are simply integers. Integer replacement fields are treated as positional indices into the argument list of the ...