Where can I find string.translate source?

Fredrik Lundh fredrik at pythonware.com
Sun Nov 20 03:41:44 EST 2005


bobueland at yahoo.com wrote:

> The module string has a function called translate. I tried to find the
> source code for that function.  In:
>
>     C:\Python24\Lib
>
> there is one file called
>
>     string.py
>
> I open it and it says
>
> """A collection of string operations (most are no longer used).
> Warning: most of the code you see here isn't normally used nowadays.
> Beginning with Python 1.6, many of these functions are implemented as
> methods on the standard string object. They used to be implemented by
> a built-in module called strop, but strop is now obsolete itself."""
>
> Inside the file string.py I couldn't find the source code for
> translate.  Where could it be?

in the string.py module, of course.

if you read that comment again, you'll notice that it says

    many of these functions are implemented as methods on the
    standard string object

and if you search for translate in string.py, you'll also find the source
code for the translate function

# Character translation through look-up table.
def translate(s, table, deletions=""):
    /... docstring snipped .../
    if deletions:
        return s.translate(table, deletions)
    else:
        # Add s[:0] so that if s is Unicode and table is an 8-bit string,
        # table is converted to Unicode.  This means that table *cannot*
        # be a dictionary -- for that feature, use u.translate() directly.
        return s.translate(table + s[:0])

which calls the translate method to do the work, just as the comment
said.

to find the method implementation, you have to look at the string object
implementation.  it's in the Objects directory in the source distribution.

</F>






More information about the Python-list mailing list