Python 101 (part 7): Dinner With A Hungry Giant - String Theory (And Other Interesting Stuff) (Page 8 of 9 ) Python comes with a whole bunch of built-in modules, which can substantially reduce the time you spend on development. Here's a list of the most common and useful ones (some of these are only available in Python 2.x): The "string" module handles common string operations,
>>> import string
>>> string.lower("HELLO")
'hello'
>>> string.center("HELLO", 80)
' HELLO
'
>>> string.split("The red wolf ate the green pumpkin", " ")
['The', 'red', 'wolf', 'ate', 'the', 'green', 'pumpkin']
>>>
while the "re" module matches regular expression via its match() and search() functions,
>>> import re
>>> re.search("at", "Batman - Dark Knight")
>>> re.findall("oo", "boom boom bang")
['oo', 'oo']
>>>
and the "difflib" and "filecmp" modules help in comparing strings, files and directories. The "math" module does for numbers what the "string" module does for strings.
>>> import math
>>> math.sin(60)
-0.304810621102
>>> math.sin(30)
-0.988031624093
>>> math.sin(0)
0.0
>>> math.cos(0)
1.0
>>> math.tan(45)
1.61977519054
>>> math.cos(90)
-0.448073616129
>>> math.hypot(3,4)
5.0
>>> math.pow(2, 4)
16.0
>>> math.exp(0)
1.0
>>>
The "cmath" and "random" modules handle complex numbers and random numbers.
>>> import cmath
>>> import rand
>>> cmath.pi
3.14159265359
>>> cmath.e
2.71828182846
>>> rand.randrange(25,100)
54
>>> rand.rand()
12992
>>> rand.choice(["Rachel", "Monica", "Chandler", "Joey", "Phoebe", "Ross"])
'Rachel'
>>> rand.choice(["Rachel", "Monica", "Chandler", "Joey", "Phoebe", "Ross"])
'Monica'
>>> rand.choice(["Rachel", "Monica", "Chandler", "Joey", "Phoebe", "Ross"])
'Joey'
>>>
The "calendar" module offers a bunch of functions to handle date-related tasks,
>>> import calendar
>>> calendar.isleap(2001)
0
>>> calendar.isleap(2000)
1
>>> calendar.weekday(2001,01,05)
4
>>> calendar.prcal(2001)
2001
January February March
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7 1 2 3 4 1 2 3 4
8 9 10 11 12 13 14 5 6 7 8 9 10 11 5 6 7 8 9 10 11
15 16 17 18 19 20 21 12 13 14 15 16 17 18 12 13 14 15 16 17 18
22 23 24 25 26 27 28 19 20 21 22 23 24 25 19 20 21 22 23 24 25
29 30 31 26 27 28 26 27 28 29 30 31
April May June
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 1 2 3 4 5 6 1 2 3
2 3 4 5 6 7 8 7 8 9 10 11 12 13 4 5 6 7 8 9 10
9 10 11 12 13 14 15 14 15 16 17 18 19 20 11 12 13 14 15 16 17
16 17 18 19 20 21 22 21 22 23 24 25 26 27 18 19 20 21 22 23 24
23 24 25 26 27 28 29 28 29 30 31 25 26 27 28 29 30
30
July August September
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 1 2 3 4 5 1 2
2 3 4 5 6 7 8 6 7 8 9 10 11 12 3 4 5 6 7 8 9
9 10 11 12 13 14 15 13 14 15 16 17 18 19 10 11 12 13 14 15 16
16 17 18 19 20 21 22 20 21 22 23 24 25 26 17 18 19 20 21 22 23
23 24 25 26 27 28 29 27 28 29 30 31 24 25 26 27 28 29 30
30 31
October November December
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7 1 2 3 4 1 2
8 9 10 11 12 13 14 5 6 7 8 9 10 11 3 4 5 6 7 8 9
15 16 17 18 19 20 21 12 13 14 15 16 17 18 10 11 12 13 14 15 16
22 23 24 25 26 27 28 19 20 21 22 23 24 25 17 18 19 20 21 22 23
29 30 31 26 27 28 29 30 24 25 26 27 28 29 30
31
>>>
while the "time" module handles time-related operations and conversions.
>>>import time
>>> time.time()
996052081.879
>>> time.localtime(time.time())
(2001, 7, 25, 14, 38, 19, 2, 206, 0)
>>>
>>> time.strftime("%A %d %B %Y", time.localtime(time.time()))
'Wednesday 25 July 2001'
>>>
The "fileinput" and "xreadlines" modules offer functions to read and process files efficiently, while the "os" module provides OS-dependent functions.
>>> import os
>>> os.getcwd()
'/home/vikram'
>>> os.getuid()
519
>>> os.getgid()
100
>>> os.uname()
('Linux', 'medusa.melonfire.com', '2.2.14-5.0', '#1 Tue Mar 7 21:07:39 EST
2000', 'i686')
>>>
The very powerful "os.path" module offers functions to manipulate and test pathnames.
>>> os.path.abspath('../')
'/home'
>>>
>>> os.path.exists('/tmp/unicorn')
0
>>> os.path.basename('/usr/local/apache')
'apache'
>>>
>>> os.path.isabs('/usr/local/apache')
1
>>> os.path.isabs('../')
0
>>>
The "pwd", "grp" and "crypt" modules offer access to the UNIX password and group files, and come in handy for user and group manipulation tasks.
>>> import pwd, grp
>>> pwd.getpwnam('vikram')
('vikram', 'x', 519, 100, '', '/home/vikram', '/bin/bash')
>>> pwd.getpwuid(519)
('vikram', 'x', 519, 100, '', '/home/vikram', '/bin/bash')
>>> grp.getgrall()
[('root', 'x', 0, []), ('bin', 'x', 1, ['bin', 'daemon']), ('daemon', 'x',
2, ['bin', 'daemon']), ('sys', 'x', 3, ['bin', 'adm']), ('adm', 'x', 4,
['adm', 'daemon']), ('tty', 'x', 5, []), ('disk', 'x', 6, []), ('lp', 'x',
7, ['daemon', 'lp']), ('mem', 'x', 8, []), ('kmem', 'x', 9, []), ('wheel',
'x', 10, [])]
>>>
The "cgi", "urllib" and "httplib" modules are used to connect your Python program to the Web; the "smtplib" and "poplib" modules help in writing mail clients; the "mimetools" module helps to process MIME-encapsulated email messages; and the "xmllib", "xml.dom" and "xml.sax" modules provide the architecture necessary to handle XML data. Whew! In case you need to find out more about a specific module - or any other Python object - consider using the dir() function, which returns a list of object attributes.
>>> import string
>>> dir(string)
['__builtins__', '__doc__', '__file__', '__name__', '_idmap', '_idmapL',
'_lower', '_re', '_safe_env', '_swapcase', '_upper', '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', 'replace', 'rfind',
'rindex', 'rjust', 'rstrip', 'split', 'splitfields', 'strip', 'swapcase',
'translate', 'upper', 'uppercase', 'whitespace', 'zfill']
>>> import math
>>> dir(math)
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2',
'ceil', 'cos', 'cosh', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp',
'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']
>>> import cgi
>>> dir(cgi)
['FieldStorage', 'FormContent', 'FormContentDict', 'InterpFormContentDict',
'MiniFieldStorage', 'StringIO', 'SvFormContentDict', '__builtins__',
'__doc__', '__file__', '__name__', '__version__', 'dolog', 'escape',
'initlog', 'log', 'logfile', 'logfp', 'maxlen', 'mimetools', 'nolog', 'os',
'parse', 'parse_header', 'parse_multipart', 'parse_qs', 'print_arguments',
'print_directory', 'print_environ', 'print_environ_usage',
'print_exception', 'print_form', 'rfc822', 'string', 'sys', 'test',
'urllib']
>>>
Every Python module has a name, which is exposed as the module attribute "__name__".
>>> import string
>>> string.__name__
'string'
>>> import math
>>> math.__name__
'math'
>>>
Remember when I told you that the default module for all your Python activities is "__main__"? You can use "__name__" to keep me honest...
>>> __name__
'__main__'
>>>
Next: Bucking The System >>
More Python Articles More By Vikram Vaswani, (c) Melonfire
|