2.8. Python’s Built-in Functions and Standard Library
This is some quick documentation of standard Python functions, modules and
objects used in Network Programming. This is by no means an exhaustive list,
nor are the explanations complete. This is intended to focus on that which is
needed for this course and not confuse the reader with information not needed.
Note
Some text on this is page was copied from the above official Python
documentation pages. To provide a more gentle introduction, in most cases
the copied text was condensed and simple examples added.
2.8.1. Data Operations
-
int(x)
Cast a variable to an integer
| Parameter: | x (long, string or float) – value to convert |
| Return type: | integer |
-
float(x)
Cast a variable to a floating point number
| Parameter: | x (integer, long or string) – value to convert |
| Return type: | float |
-
str(x)
Convert a variable to a string
| Parameter: | x (integer, long or most any object) – value to convert |
| Return type: | string |
Note that most classes include a __str__() method, which returns an
appropriate string representation of the object. Python calls this method when
str(obj) is called.
-
min(iterable[, args...])
- With a single argument iterable, return the smallest item of a non-empty
iterable (such as a string, tuple or list). With more than one argument,
return the smallest of the arguments.
-
max(iterable[, args...])
- With a single argument iterable, return the largest item of a non-empty
iterable (such as a string, tuple or list). With more than one argument,
return the largest of the arguments.
2.8.2. Functions for Working with Python Itself
-
dir(module)
- Returns a list of strings containing the names of all the attributes (data
and methods) contained in the module.
2.8.3. Built-in List Operations
-
class list
Built-in sequence storage container
-
del s[i]
- Remove item i from list s
-
append(x)
- s.append(x) – Add item x to end of list s
-
extend(x)
- s.extend(x) – Add items from list x to the end of list s
-
count(x)
- s.count(x) – Return number of i‘s for which s[i] == x
-
index(x)
- s.index(x) – return smallest k such that s[k] == x
-
insert(x)
- s.insert(i, x) – add item x to s at position i, such that
s[i] == x
-
pop(x)
- s.pop([i]) – Remove and return item from s, at position i.
Default value of i is len(s) - 1, which is also -1 (the last
item). Same as x = s[i]; del s[i]; return x
-
remove(x)
- s.remove(x) – Remove the first item from s whose value is x.
Same as del s[s.index(x)]
-
reverse(x)
- s.reverse() – reverses the items of s in place
-
sort(x)
- s.sort([cmp[, key[, reverse]]]) – sort the items of s in place
2.8.4. Built-in Dictionary Operations
-
class dict
Built-in dictionary (associative array) storage container
-
len(d)
- Return the number of items in the dictionary d.
-
d[key]
- Return the item of d with key key. Raises a KeyError if key
is not in the map.
-
d[key] = value
- Set d[key] to value.
-
del d[key]
- Remove d[key] from d. Raises a KeyError if key is not in
the map.
-
key in d
- Return True if d has a key key, else False.
-
key not in d
- Equivalent to not key in d.
-
iter(d)
- Return an iterator over the keys of the dictionary. This is a shortcut
for iterkeys().
-
clear()
- Remove all items from the dictionary.
-
copy()
- Return a shallow copy of the dictionary.
-
fromkeys(seq[, value])
Create a new dictionary with keys from seq and values set to value.
fromkeys() is a class method that returns a new dictionary. value
defaults to None.
-
get(key[, default])
- Return the value for key if key is in the dictionary, else default.
If default is not given, it defaults to None, so that this method
never raises a KeyError.
-
has_key(key)
- Test for the presence of key in the dictionary. has_key() is
deprecated in favor of key in d.
-
items()
- Return a copy of the dictionary’s list of (key, value) pairs.
-
iteritems()
- Return an iterator over the dictionary’s (key, value) pairs.
-
iterkeys()
- Return an iterator over the dictionary’s keys.
-
itervalues()
- Return an iterator over the dictionary’s values.
-
keys()
- Return a copy of the dictionary’s list of keys.
-
pop(key[, default])
- If key is in the dictionary, remove it and return its value, else return
default. If default is not given and key is not in the dictionary,
a KeyError is raised.
-
popitem()
- Remove and return an arbitrary (key, value) pair from the dictionary.
-
setdefault(key[, default])
- If key is in the dictionary, return its value. If not, insert key
with a value of default and return default. default defaults to
None.
-
update([other])
- Update the dictionary with the key/value pairs from other, overwriting
existing keys. Return None.
-
values()
- Return a copy of the dictionary’s list of values.
2.8.5. string Manipulations
Note
Functions from the string module operate on data type objects of
type str. Because str is a sequence type, meaning that it can used
in a for loop and in slicing operations (see Python Data Containers),
one might think of a string as a mutable data container, such as
Built-in List Operations. However, like other built-in data types, such as int and
float, the str class defines an immutable data type. This
means that an assignment statement must be used to modify a string:
>>> import string
>>> st = "Bob"
>>> st.replace('ob','ill') # This only displays the returned value
'Bill'
>>> st
'Bob'
>>> st = st.replace('ob','ill') # An assignment makes a change
>>> st
'Bill'
It is common to see string module functions expressed in one of two ways:
>>> import string
>>> st = "Hello, world"
>>> st = st.replace('world', 'class')
>>> st1 = string.replace(st, 'Hello', 'Good night')
>>> print st, '--', st1
Hello, class -- Good night, class
The first syntax, which uses the object_name.method() notation, is
more commonly used than the later. However, to make it clear that these
functions are part of the string module and to be consistent with the
official Python documentation of string functions,
the later notation is used. In each case, the variable st represents
the string being operated on.
-
string.replace(st, old, new)
- Return a copy of string st with all occurrences of substring old
replaced by new.
-
string.join(st, seq)
Return a string which is the concatenation of the strings in the sequence
seq. The separator between elements is st. join() is often used
with a string literal, which appears a little strange the first time ones
sees it:
>>> se = ['And', 'now,', 'for', 'something', 'completely', 'different']
>>> st = ' '.join(se)
>>> st
'And now, for something completely different'
-
string.split(st[, sep])
Return a list of the words of the string st. If the optional second
argument sep is absent, the words are separated by arbitrary strings of
whitespace characters (space, tab, newline). If the second argument sep
is present, it specifies a string to be used as the word separator.
>>> st = "I like pizza"
>>> st.split()
['I', 'like', 'pizza']
>>> st.split('i')
['I l', 'ke p', 'zza']
-
string.startswith(st, prefix)
- Return True if st starts with the prefix, otherwise return
False.
-
string.strip(st)
- Return a copy of string st with all leading and trailing whitespace
characters removed. If st may contain some spaces and newline characters
at the beginning or end, strip() is useful to get just the content
characters of the string.