How to replace multiple-line text

Alex Martelli aleax at aleax.it
Fri Jul 12 04:56:40 EDT 2002


David Lees wrote:

> Thank you kindly Alex for this solution.  This is the problem that I had

You're welcome!

> in mind.  You also taught me something rather basic about Python that I
> misunderstood  I thought that to use string methods I needed to import
> the string class and then use it like this:
> 
>>>> import string
>>>> x='this is junk'
>>>> string.replace(x,'junk','stuff')
> 'this is stuff'
> 
> Time to do some more reading on classes, since I don't understand why it
> is not necessary to import string here.

'string' is a module, not a class.  "import string" loads the module (if
it wasn't already loaded) and makes the module object available, with
name 'string', in the current namespace.

The class (type) is named 'str', and you never need to do anything strange
to access it because it's a builtin name, always available.

But when you have an instance of any type, you never need to get the
type -- you can just call methods directly on the instance.  This is
part of object-oriented programming -- you have the object (that is,
the instance), you don't need to access types or modules to call the
object's methods -- just do it.

Module string does offer functions named just like the methods of
str instances (string objects), for historical reasons -- it used to
be, until a few years ago, that string objects had no methods, so
you HAD to import string and call its functions back then.  To avoid
breaking old working code, you still CAN work that way, but there's
no need at all to do that in new code.  If you look at string.py in
the directory where you keep your Python library (C:\Python22\Lib, say)
you'll see a lot of code such as:

def lower(s):
    return s.lower()

i.e., the function is just a thin wrapper over the object's method,
and delegates everything to the object's method -- it's pure (if
small) overhead and exists only for backwards compatibility.


Alex




More information about the Python-list mailing list