Python Notes : Input and Output
Fancier Output Formatting
several ways to format output
  • to use formatted string literals begin a string with f or F before the opening quotation mark or triple quotation mark
    in string can write a Python expression between { and } characters that can refer to variables or literal values
    >>> year = 2016
    >>> event = 'Referendum'
    >>> f'Results of the {year} {event}'
    'Results of the 2016 Referendum'
  • The str.format() method of strings still uses { and } to mark where a variable will be substituted
    can provide detailed formatting directives
    need to provide the information to be formatted
    >>> yes_votes = 42_572_654
    >>> total_votes = 85_705_149
    >>> percentage = yes_votes / total_votes
    >>> '{:-9} YES votes  {:2.2%}'.format(yes_votes, percentage)
    ' 42572654 YES votes  49.67%'
    see Format Specification Mini-Language for formatting directives
  • DIY all the string handling by using string slicing and concatenation operations
    the string type has some methods that perform useful operations for padding strings to a given width
string type has two distinct representations
the str() function is meant to return representations of values which are fairly human-readable
repr() generates representations which can be read by the interpreter
>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
>>> print(s)
The value of x is 32.5, and y is 40000...
>>> # The repr() of a string adds string quotes and backslashes:
>>> hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, world\n'
>>> # The argument to repr() may be any Python object:
>>> repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"
Formatted String Literals
Formatted string literals aka f-strings
can include the value of Python expressions inside a string by prefixing the string with f or F and writing expressions
an optional format specifier can follow the expression
passing an integer following the colon sets the number of characters wide of the expression
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
other modifiers can be used to convert the value before it is formatted the = specifier can be used to expand an expression to the text of the expression
>>> bugs = 'roaches'
>>> count = 13
>>> area = 'living room'
>>> print(f'Debugging {bugs=} {count=} {area=}')
Debugging bugs='roaches' count=13 area='living room'
The String format() Method
basic use of str.format()
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!
the brackets are called format fields
a number in the brackets can be used to refer to the position of the object passed into the str.format() method
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
keyword arguments can be used in the str.format() method
>>> print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
positional and keyword arguments can be arbitrarily combined
>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='George'))
The story of Bill, Manfred, and George.
can reference the variables to be formatted by name instead of by position
pass the dict as an arg and use square brackets '[]' to access the keys
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
...      'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
can also be done by passing the table dictionary as keyword arguments with the ** notation
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
the built-in function vars() returns a dictionary containing all local variables
>>> table = {k: str(v) for k, v in vars().items()}
>>> message = " ".join([f'{k}: ' + '{' + k +'};' for k in table.keys()])
>>> print(message.format(**table))
__name__: __main__; __doc__: None; __package__: None; __loader__: ...
Manual String Formatting
print() always adds spaces between its arguments
str.rjust() returns right-justifies a string in a field of a given width by padding it with spaces on the left
str.ljust() returns left-justifies
str.center()returns centered in a string with padding using specified fillchar
str.zfill()pads a numeric string on the left with zeros
Old String Formatting
The % operator (modulo) can be used for string formatting
given format % values % conversion specifications in format are replaced with zero or more elements of values
commonly known as string interpolation
>>> import math
>>> print('The value of pi is approximately %5.3f.' % math.pi)
The value of pi is approximately 3.142.
Reading and Writing Files
open() returns a file object
commonly used with two positional arguments and one keyword argument open(filename, mode, encoding=None)
>>> f = open('workfile', 'w', encoding="utf-8")
mode arguments
  • r - default, file will only be read
  • w - new file will be written and overwrites any existing file
  • a - open file for appending
  • r+ - open file for reading and writing
use with keyword with whenworking with files
>>> with open('workfile', encoding="utf-8") as f:
...    read_data = f.read()

>>> # can check that the file has been automatically closed
>>> f.closed
True
Methods of File Objects
use f.read(size) to read a file's contents, call f.read(size)
reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode)
when size arg is omitted or negative, the entire file will be read and returned
if EOF haas been reach f.read() will return an empty string

f.readline() reads a single line from the file
a newline character is left at the end of the string
character is only omitted on the last line if the file doesn't end in a newline
a blank line is represented by a string containing only a single newline
can loop through a file object

>>> for line in f:
...    print(line, end='')

This is the first line of the file.
Second line of the file
f.write(string) writes the contents of string to the file and returning the number of characters written
other types need to be converted either to a string (in text mode) or a bytes object (in binary mode) before writing them
>>> value = ('the answer', 42)
>>> s = str(value)  # convert the tuple to string
>>> f.write(s)
18
f.tell() returns an integer giving the file object's current position
represents the number of bytes from the beginning of the file when in binary mode and an opaque number when in text mode
change cursor position use f.seek(offset, whence)
whence value determines the point of reference for offset
  • 0 - offset from beginning of file
  • 1 - offset from current position
  • 2 - offset from end of file
Saving Structured Data with json
read() method only returns strings
parsing and serializing complex data types like nested lists and dictionaries by hand can be complicated
instead use json to serialize and deserialize data
view its JSON string representation with a simple line of code
>>> import json
>>> x = [1, 'simple', 'list']
>>> json.dumps(x)
'[1, "simple", "list"]'
dump() method serializes the object to a text file.
f is a text file object opened for writing
json.dump(x, f)
to decode file open for reading
x = json.load(f)
previous    index    next