1. Home
  2. Computing & Technology
  3. Python

Beginning Python: Putting It All Together With Syntax

From Al Lukaszewski, for About.com

9 of 10

Modules - Part 1: Importing Modules From the Python Library

Modules are pieces of Python code that you import into your programs. When taken from the Python Standard Library, these are boiler-plate functions that are optimized for a particular task.

Some important Python modules are 're' for pattern matching (i.e., regular expressions), 'string' for string handling, 'sys' for system-specific functions, and 'os' for other operating system functions. To import one of these, simply write 'import' and the library you want to import:

import re
import string
import sys
import os

There is no specific order in which you must import them, but you must import them before you use any functions which they contain. If you would rather import all of them on a single line, you can:

import re, string, sys, os

Sometimes the module itself is so large that importing the whole thing can bog down the program upon execution. This is particularly true of the posix module. In this case, it is better to import specific functions as follows:

from posix import environ
For most operating system services, however, it is best to use the os module, which is platform independent.

Once a module is imported, preface the function calls with the name of that module: [blockquote] new1 = re.match('\t', variable)
new2 = string.sub('\t', '_|_|_|_|', varibale) [/blockquote]

From the Python shell, if you do not know what functions are supported by the module, call dir() to receive a list of them:

>>> import string
>>> dir(string)
['Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', '__name__', '_float', '_idmap', '_idmapL', '_int', '_long', '_multimap', '_re', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'atof', 'atof_error', 'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'digits', 'expandtabs', 'find', 'hexdigits', 'index', 'index_error', 'join', 'joinfields', 'letters', 'ljust', 'lower', 'lowercase', 'lstrip', 'maketrans', 'octdigits', 'printable', 'punctuation', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitfields', 'strip', 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill']
Obviously, this is just to refresh your memory and not to replace the reference documentation.

Explore Python
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Python
  4. Python Library
  5. Modules - Part 1: Importing Modules From the Python Library

©2009 About.com, a part of The New York Times Company.

All rights reserved.