CompSci 6, Fall 2011
Python Summary

Python Help for Compsci 6/101

On this page we'll keep track of the Python types, functions, and operators that we've covered in class. You should also review the online Python References for more complete coverage.

Mathematical Operators
Symbol Meaning Example
+ addition 4 + 5 = 9
- subtraction 9 - 5 = 4
* multiplication 3*5 = 15
/ division 6/3 = 2
6/4 = 1
6.0/4 = 1.5
% mod/remainder 5 % 3 = 2
** exponentiation 3**2 = 9, 2**3 = 8
String Operators
+ concatenation "ab"+"cd"="abcd"
* repeat "xo"*3 = "xoxoxo"
Comparison Operators
== is equal to 3 == 3 is True
!= is not equal to 3 != 3 is False
>= is greater than or equal to 4 >= 3 is True
<= is less than or equal to 4 <= 3 is False
> is strictly greater than 4 > 3 is True
< is strictly less than 3 < 3 is False
Boolean Operators
x=5
not flips the value of a bool (not x == 5) is False
and returns True only if both parts of it are True (x > 3 and x < 7) is True
(x > 3 and x > 7) is False
or returns True if at least one part of it is True (x < 3 or x > 7) is False
(x < 3 or x < 7) is True
Type Conversion Functions
int(x) turn x into an integer value int("123") == 123
  int can fail, e.g., int("abc") raises an error
float(x) turn x into an float value float("2.46") == 2.46
  float can fail, e.g., float("abc") raises an error
str(x) turn x into a string value str(432) == "432"
type(x) the type of x type(1) == int
type(1.2) == float
String Functions
s="colorful"
Name Returns Example
.find(str) index of first occurrence s.find("o") == 1
s.find("e") == -1
.count(str) number of occurrences s.count("o") == 2
s.count("r") == 1
s.count("e") == 0
.strip() copy with leading/trailing whitespace removed "   big ".strip() == "big"
.split() list of "words" in s "big bad dog".split() == ["big","bad", "dog"]
.split(",") list of "items " in s that are separated by a comma
In general can split on any string, not just a comma, e.g., s.split(":") will split on a colon and s.split("gat") will split on the string "gat".
"this,old,man".split(",") == ["this", "old", "man"]
.startswith(str) boolean if starts with string s.startswith("color") == True
s.startswith("cool") == False
.upper() uppercase of s s.upper() == "COLORFUL"
.lower() lowercase of s "HELLO".lower() == "hello"
.capitalize() capitalized s s.capitalize() == "Colorful"
Miscellaneous Functions
help(x) documentation for module x  
len(x) length of sequence x, e.g., String/List len("duke") == 4
sorted(x) return list that is sorted version of sequence/iterable x, doen't change x sorted("cat") == ['a','c','t']
range(x) a list of integers starting at 0 and going up to but not including x range(5) == [0, 1, 2, 3, 4]
range(start, stop) a list of integers starting at start and going up to but not including stop range(3, 7) == [3, 4, 5, 6]
min(x, y, z) minimum value of all arguments min(3, 1, 2) == 1
min("z", "b", "a") == "a"
max(x, y, z) maximum value of all arguments max(3, 1, 2) == 3
max("z", "b", "a") == "z"
abs(x) absolute value of the int or float x abs(-33) == 33
abs(-33.5) == 33.5
List Functions
sum(lst) returns sum of elements in list lst sum([1,2,4]) == 7
max(lst) returns maximal element in lst max([5,3,1,7,2]) == 7
lst.append(...) append an element to lst, changing lst [1,2,3].append(8) == [1,2,3,8]
lst.extend(lst2) append every element of lst2 to lst [1,2,3].extend([8,9]) == [1,2,3,8,9]
lst.sort() sorts the elements of lst
lst.index(elt) return index of elt in lst, error if elt not in lst [1,5,3,8].index(5) == 1
lst.count(elt) return number of occurrences of elt in lst [1,2,1,2,3].count(1) == 2
lst.pop(index) remove and return element at position index in lst, so has side-effect of altering list and returns value. Default index is last value.
Math Functions (import math)
math.pi 3.1415926535897931
math.sqrt(num) returns square root of num as float math.sqrt(9) == 3.0
Random Functions (import random)
random.choice(list_of_choices) returns a random element from list_of_choices. Gives an error if list_of_choices has length 0.
random.randint(start, end) Returns a random integer between start and end. Unlike range() and list slicing, the largest value it can return is end, not end-1.
random.random() Returns a random float between 0 and 1.
Set Functions
s.add(item) adds the item into the set, and returns nothing.
s.union(t) returns new set representing s UNION t, i.e., all elements in either s OR t, t can be any iterable (e.g., a list)
s.intersection(t) returns new set representing s INTERSECT t, i.e., only elements in both s AND t, t can be any iterable (e.g., a lsit)
s | t returns/evaluates to union of s and t, both must be sets.
s & t returns/evaluates to intersection of s and t, both must be sets.
s - t returns/evaluates to set with all elements in s that are not int
Dictionary Functions
d[key] returns the value associated with key, error if key not in dictionary d
d.get(key) returns value associated with key, error if key not in dictionary d
d.get(key,default) returns value associated with key, returns default if key not in d
d.keys() returns a list/view of the keys in dictionary
d.items() returns a list/view of tuples, (key,item) pairs from dictionary
d.values() returns a list/view of values in dictionary
Regular Expression Pattern Power Characters (import re)
\d match any digit, equivalent to [0-9] '\d' matches '0', but not 'a'
\w match any "word" character, i.e., letter, digit, or underbar: equivalent to [a-zA-Z0-9_] '\w' matches 'a' or '_', but not '+'
. match any kind of character '...' matches any three characters
^ match at the start of the pattern '^x' matches any text that starts with an x
$ match at the end of the pattern 'x$' matches any text that ends with an x
+ match 1 or more occurrences of the pattern to its left 'i+' matches 'igloo' and 'radii',
but not 'apple'
* match 0 or more occurrences of the pattern to its left '\d*.\d' matches '10.1' and '.9',
but not 'a.b'
() capture matched text as well as the starting and ending index of the text '(\w) (\d)' matches 'a 0' and allows you to access the matches 'a' and '0' later
? match 0 or 1 occurrences of the pattern to its left '0?1' matches '101' and '11', but not '1001'

Regular Expression Functions (import re)

re.compile(regex)

compiles given string into pattern object, PAT, which have various matching or changing methods

PAT.sub(replacement, str) find all substrings in given string where the pattern matches and replaces them with replacement string
PAT.findall(str) find all substrings in given string where pattern matches, returns them as a list
PAT.search(str) find all locations in given string where pattern matches, returns match object, MAT, or None
MAT.group() return matching substring for the originally compiled regex pattern
MAT.start()
MAT.end()
return the indices of the start and end of the matching substring