...

/

Formatting Strings

Formatting Strings

We'll cover the following...

Let’s take another look at humansize.py:

Press + to interact
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 bytes
a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024
if False, use multiples of 1000
Returns: string
''' #③
if size < 0:
raise ValueError('number must be non-negative') #④
multiple = 1024 if a_kilobyte_is_1024_bytes else 1000
for suffix in SUFFIXES[multiple]:
size /= multiple
if 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.

Press + to interact
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 ...

Access this course and 1400+ top-rated courses and projects.