CS 111 f21 — Useful Python Stuff

1 Format Strings

  • useful way to produce nicely-formatted text output
  • use {} to indicate a hole to be filled in
  • then use format method on that string to provide the values to fill in
x = 10
y = 4
# two clunky ways to get the spacing right
print("Location: (", x, ", ", y, ")", sep="")
print("Location: (" + str(x) + ", " + str(y) + ")")

# using format string
print("Location: ({}, {})".format(x, y))
  • can do all sorts of handy things like control the number of decimal places, convert to a percentage, and add commas to separate thousands
points = 19
total = 22
print("score:", points/total)
print("score: {:.4f}".format(points/total))
print("score: {:.2%}".format(points/total))

print("{:,}".format(1234567890))
  • they can also align output (see prisoner2.py and prisoner3.py for more examples—I used format strings to produce the table of results for the --log option
print('{:<30}'.format('left aligned'))
print('{:>30}'.format('right aligned'))
print('{:^30}'.format('centered'))
print('{:*^30}'.format('centered'))  # use '*' as a fill char
  • format strings can even access arguments attributes or elements
p = Point(3, 8)
print("p is a Point at ({0.x}, {0.y})".format(p))

nums = [4,2,5,7]
print("{0[0]} is the first elements and {0[-1]} is the last".format(nums))

2 Multiplying a Sequence

  • multiplying a sequence by an integer produces a new sequence with the original duplicated that number of times
v = [2,4,6]
s = "*"
print(v*3)
print(s*50)

3 Multiple Assignment

  • Python allows multiple assignments as part of a single statement
  • the value on the right of the = must be a sequence with elements that can be matched up with each variable name on the left
nums = [0, 2, 4]
x, y, z, = nums
print(x)
print(y)
print(z)
  • makes it easy to have a function that returns multiple values
def f(x):
    return (x*2, x*3)
a, b = f(5)
print(a, b)
  • we can also have a for loop with multiple loop variables
d = {"a": 1, "b": 2, "c": 3}
for key, value in d.items():
    print(key, "has a value of", value)

4 Conditional Expressions

  • Python lets us write an expression that can have one of two values depending on a condition
if count == steps:
    count = 0
else:
    count += 1

becomes

count = 0 if count == steps else count + 1

5 List Comprehensions

  • a single expression that generates a new sequence from an existing sequence
import random
r = [random.random() for i in range(10000)]
  • can incorporate conditional expressions to filter the sequence

For example, this function takes a list of strings, maps the string method capitalize to the elements, and returns a new list of strings:

def capitalize_all(t):
    res = []
    for s in t:
        res.append(s.capitalize())
    return res

def capitalize_all(t):
    return [s.capitalize() for s in t]

For example, this function selects only the elements of t that are upper case, and returns a new list:

def only_upper(t):
    res = []
    for s in t:
        if s.isupper():
            res.append(s)
    return res

def only_upper(t):
    return [s for s in t if s.isupper()]