Examining names

When working in interactive mode, you sometimes need to be reminded what names you've given to objects. The dir() function, which is built into interactive mode, lists the names (such as names of data objects, module names, and function names) that are stored in the interactive mode's namespace at any particular point in your coding session. (Namespace is a Python term for a list of names that a particular part of a program knows about.) Tip You can also use the dir() function to examine the...

Getting field values from a table

To get field values from a table, you execute a query specifying the data you want and then use the fetchall() method to retrieve the data. (You may have noticed by now that most SQLite tasks involve executing a query.) This example retrieves a list of all the values stored in our table's name field > > > cursor.execute(select name from address) < sqlite3.Cursor object at 0x66830> > > > print cursor.fetchall() (u'Pet Shops Ltd',), (u'Similar Pet Shops Ltd',) The fetchall()...

Under One Condition

Conditional expressions were added to Python 2.5 to simplify choosing one of two options in an expression. (See Chapter 10.) A conditional expression takes the following form 2. Action depends on whether C is true o If C is true, then X is evaluated to give the result. o If C isn't true, Y is evaluated to give the result. You can use parentheses in conditional expressions. Because parentheses identify the conditional expression as a single unit, they make it easier to read in context of other...

Tuple unpacking

Unpacking a tuple means giving a different name to each element of the tuple. Tuple unpacking is useful because many functions in Python, such as the zip function described in the previous Building lists incrementally section, return tuples. With tuple unpacking, you can easily get at the individual items in these tuples. To unpack a tuple, just assign multiple names on a single line. Put the names you want to unpack into on the left side of the assignment statement and put the tuple on the...

Getting Close Enough with difflib

People often make mistakes when entering text. The difflib module gives you a way to find strings that are close but not exact matches to a given string gt gt gt right 'The quick brown fox' gt gt gt wrong 'THe quack brown fix' gt gt gt matcher difflib.SequenceMatcher None, right, wrong The ratio method returns a floating point number between 0 and 1 that indicates how close the match is. Higher numbers indicate a closer match. A match higher than 0.6 is usually considered good maybe not by...