[Tutor] Library reference

Jeff Shannon jeff@ccvcorp.com
Mon, 17 Jun 2002 11:09:10 -0700


Terje Johan Abrahamsen wrote:

> I run PythonWin 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on
> win32. (from first line when started) And I am now looking through the
> Python Library Referece release 2.2.1. On page 17-19 there are string
> methods. So, I assume that to get access, I write:
> >>>import string
> >>>from string import*

First of all, there is a subtle but important distinction between "string
methods" and the "string module".  When you type 'import string', you're getting
access to the string module, and you use the functions in it by typing, for
instance,

>>> mylist = string.split(mystring)

The second line that you've typed ('from string import *') is unnecessary and
probably a bad idea.  What that does to take all the functions in the string
module's namespace and insert them into the current namespace.  This *might*
seem handy, because now instead of typing string.split() you only need to type
split() ... but this is often a trap.  :)  If you have any *other* function
named split() in your current namespace, then you'll only be able to access
*one* of them -- whichever was bound last.  The worst part of this is that you
don't really *know* what names the string module uses, so you're just hoping
that none of those names will conflict with any other names you're using.  And
if there *are* any conflicts, there's a chance that it will be subtle enough
that you'll never notice the difference until you're running a marathon
debugging session to track down some odd erratic behavior in your latest big
project...  In short, best to avoid using the 'from somemodule import *' idiom
unless you're *sure* that the module was designed for that.


> But, I can not use all the string methods that are described.
> For example, string.istitle() doesn't work. It cannot find it. Encode() is
> not found either. How can I use these and others? Eg capitalize() does work.
> I can't see any note saying that you have to do something different to use
> capitalize() than title() in the library ref. What do I do wrong?

Now, as I mentioned before, string *methods* are different from module string.
String methods are called just like other object methods -- by using an object
reference as a qualifier, and in this case, the object should be a string.

What you were doing is, I presume, something like this:

>>> import string
>>> string.istitle("I Am A String")
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
AttributeError: 'module' object has no attribute 'istitle'

...but istitle() is not part of the string module, it's a string method.  Try
this instead:

>>> "I Am A String".istitle()
1
>>> "I am a string".istitle()
0
>>> mystring = "I Am A String"
>>> mystring.istitle()
1
>>>

Does that make more sense now?  :)

Jeff Shannon
Technician/Programmer
Credit International