Python 101 - Introduction to Python
By Dave Kuhlman2005-07-02
Data Types
Strings
What
In Python, strings are immutable sequences of characters. They are immutable in that in order to modify a string, you must produce a new string.
When
Any text information.
How
Create a new string from a constant:
s1 = 'abce'
s2 = "xyz"
s3 = """A
multi-line
string.
"""
Use any of the string methods, for example:
>>> 'The happy cat ran home.'.upper()
'THE HAPPY CAT RAN HOME.'
>>> 'The happy cat ran home.'.find('cat')
10
>>> 'The happy cat ran home.'.find('kitten')
-1
>>> 'The happy cat ran home.'.replace('cat', 'dog')
'The happy dog ran home.'
Type "help(str)" or see http://www.python.org/doc/current/lib/string-methods.html for more information on string methods.
You can also use the equivalent functions from the string module. For example:
>>> import string
>>> s1 = 'The happy cat ran home.'
>>> string.find(s1, 'happy')
4
See http://www.python.org/doc/current/lib/module-string.htmlfor more information on the string module.
There is also a string formatting operator: "%".
>>> state = 'California'
>>> 'It never rains in sunny %s.' % state
'It never rains in sunny California.'
You can use any of the following formatting characters:
| Conversion | Meaning | Notes |
|---|---|---|
| d | Signed integer decimal. | |
| i | Signed integer decimal. | |
| o | Unsigned octal. | (1) |
| u | Unsigned decimal. | |
| x | Unsigned hexidecimal (lowercase). | (2) |
| X | Unsigned hexidecimal (uppercase). | (2) |
| e | Floating point exponential format (lowercase). | |
| E | Floating point exponential format (uppercase). | |
| f | Floating point decimal format. | |
| F | Floating point decimal format. | |
| g | Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise. | |
| G | Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise. | |
| c | Single character (accepts integer or single character string). | |
| r | String (converts any python object using repr()). | (3) |
| s | String (converts any python object using str()). | (4) |
| % | No argument is converted, results in a "%" character in the result. |
And these flags:
| Flag | Meaning |
|---|---|
| # | The value conversion will use the ``alternate form'' (where defined below). |
| 0 | The conversion will be zero padded for numeric values. |
| - | The converted value is left adjusted (overrides the "0" conversion if both are given). |
| (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion. | |
| + | A sign character ("+" or "-") will precede the conversion (overrides a "space" flag). |
See http://www.python.org/doc/current/lib/typesseq-strings.htmlfor more information on string formatting.
You can also write strings to a file and read them from a file. Here are some examples:
- Writing - For example:
>>> outfile = file('tmp.txt', 'w')
>>> outfile.write('This is line #1\n')
>>> outfile.write('This is line #2\n')
>>> outfile.write('This is line #3\n')
>>> outfile.close()Notes:
- Note the end-of-line character at the end of each string.
- The file constructor creates a file object. It takes as arguments (1) the file name and (2) a mode. Commonly used modes are "r" (read), "w" (write), and "a"(append). See http://www.python.org/doc/current/lib/built-in-funcs.htmlfor more modes and more on file.
- Reading an entire file:
>>> infile = file('tmp.txt', 'r')
>>> content = infile.read()
>>> print content
This is line #1
This is line #2
This is line #3
>>> infile.close() - Reading a file one line at a time:
>>> infile = file('tmp.txt', 'r')
>>> for line in infile.readlines():
... print 'Line:', line
...
Line: This is line #1
Line: This is line #2
Line: This is line #3
>>> infile.close()Notes:
- "infile.readlines()" returns a list of lines in the file. For large files use the file object itself or "infile.xreadlines()", both of which are iterators for the lines in the file.
A few additional comments about strings:
- A string is a special kind of sequence. So, you can index into the characters of a string and you can iterate over the characters in a string. For example:
>>> s1 = 'abcd'
>>> s1[1]
'b'
>>> s1[2]
'c'
>>> for ch in s1:
... print ch
...
a
b
c
d - If you need to do fast or complex string searches, there is a regular expression module in the standard library: re.
- An interesting feature of string formatting is the ability to use dictionaries to supply the values that are inserted. Here is an example:
names = {'tree': 'sycamore', 'flower': 'poppy', 'herb': 'arugula'}
print 'The tree is %(tree)s' % names
print 'The flower is %(flower)s' % names
print 'The herb is %(herb)s' % names
Sequences
What
There are several types of sequences in Python. We've already discussed strings. In this section we will describe lists and tuples. See http://www.python.org/doc/current/lib/typesseq.html for a description of the other sequence types (e.g. buffers and xrange objects).
Lists are dynamic arrays. They are arrays in the sense that you can index items in a list (for example "mylist[3]") and you can select sub-ranges (for example "mylist[2:4]"). They are dynamic in the sense that you can add and remove items after the list is created.
Tuples are light-weight lists, but differ from lists in that they are immutable. That is, once a tuple has been created, you cannot modify it. You can, of course, modify any (modifiable) objects that the tuple refers to.
Capabilities of lists:
- Append items.
- Insert items.
- Add a list of items.
Capabilities of lists and tuples:
- Index items.
- Select a subsequence of items (also known as a slice).
- Iterate over the items in the list or tuple.
When
- Whenever you want to process a colletion of items.
- Whenever you want to iterate over a collection of items.
- Whenever you want to index into a collection of items.
How
To create a list use:
>>> items = [111, 222, 333]
>>> items
[111, 222, 333]
To add an item to the end of a list, use:
>>> items.append(444)
>>> items
[111, 222, 333, 444]
To insert an item into a list, use:
>>> items.insert(0, -1)
>>> items
[-1, 111, 222, 333, 444]
You can also push items onto the right end of a list and pop items off the right end of a list with append and pop.
>>> items.append(555)
>>> items
[-1, 111, 222, 333, 444, 555]
>>> items.pop()
555
>>> items
[-1, 111, 222, 333, 444]
And, you can iterate over the items in a list with the for statement:
>>> for item in items:
... print 'item:', item
...
item: -1
item: 111
item: 222
item: 333
item: 444
Dictionaries
What
Associative arrays.
Capabilities:
- Ability to iterate over keys or values.
- Ability to add key-value pairs dynamically.
- Look-up by key.
For help on dictionaries, type:
>>> help dict
at Python's interactive prompt, or:
$ pydoc help
at the command line.
When
- When you need look-up by key.
- When you need a "structured" lite-weight object or an object with named fields. (But, don't forget classes.)
- When you need to map a name or label to any kind of object, even an executable one such as a function.
How
Create a dictionary with:
>>> lookup = {}
>>> lookup
{}
or:
>>> def fruitfunc():
... print "I'm a fruit."
>>> def vegetablefunc():
... print "I'm a vegetable."
>>>
>>> lookup = {'fruit': fruitfunc, 'vegetable': vegetablefunc}
>>> lookup
{'vegetable': <function vegetablefunc at 0x4028980c>,
'fruit': <function fruitfunc at 0x4028e614>}
>>> lookup['fruit']()
I'm a fruit.
>>> lookup['vegetable']()
I'm a vegetable.
or:
>>> lookup = dict((('aa', 11), ('bb', 22), ('cc', 33)))
>>> lookup
{'aa': 11, 'cc': 33, 'bb': 22}
>>>
Test for the existence of a key with:
>>> if lookup.has_key('fruit'):
... print 'contains key "fruit"'
...
contains key "fruit"
>>>
or:
>>> if 'fruit' in lookup:
... print 'contains key "fruit"'
...
contains key "fruit"
>>>
Access the value of a key as follows:
>>> print lookup['fruit']
<function fruitfunc at 0x4028e614>
>>>
>>> for key in lookup:
... print 'key: %s' % key
... lookup[key]()
...
key: vegetable
I'm a vegetable.
key: fruit
I'm a fruit.
>>>
And, remember that you can sub-class dictionaries. Here are two versions of the same example. The keyword arguments in the second version require Python 2.3:
#
# This example works with Python 2.2.
class MyDict_for_python_22(dict):
def __init__(self, **kw):
for key in kw.keys():
self[key] = kw[key]
def show(self):
print 'Showing example for Python 2.2 ...'
for key in self.keys():
print 'key: %s value: %s' % (key, self[key])
def test_for_python_22():
d = MyDict_for_python_22(one=11, two=22, three=33)
d.show()
test_for_python_22()
#
# This example works with Python 2.3.
# Keyword support, when subclassing dictionaries, seems to have
# been enhanced in Python 2.3.
class MyDict(dict):
def show(self):
print 'Showing example for Python 2.3 ...'
for key in self.keys():
print 'key: %s value: %s' % (key, self[key])
def test():
d = MyDict(one=11, two=22, three=33)
d.show()
test()
Running this example produces:
Showing example for Python 2.2 ...
key: one value: 11
key: three value: 33
key: two value: 22
Showing example for Python 2.3 ...
key: three value: 33
key: two value: 22
key: one value: 11
A few comments about this example:
- The class MyDict does not define a constructor (__init__). This enables us to re-use the contructor from dict and any of its forms. Type "help dict" at the Python interactive prompt to learn about the various ways to call the dict constructor.
- The show method is the specialization added to our sub-class.
- In our sub-class, we can refer to any methods in the super-class (dict). For example: "self.keys()".
- In our sub-class, we can refer the dictionary itself. For example: "self[key]".
Tutorial Pages:
» Python 101 -- Introduction to Python
» Interactive Python
» Data Types
» Simple Statements
» Control Structures
» Organization
Copyright (c) 2003 Dave Kuhlman
| Related Tutorials: » Python and Java - A Side by Side Comparison » Learn Python in 10 Minutes » Python 201 - (Slightly) Advanced Python Topics » Google Sitemaps » Python 101 » Python vs. Perl |
