pythonpython-3.xpython-2.7python-2to3

Are there differences between string.replace / .strip / .find and the built-in functions?


I have a Python 2 codebase which I'm migrating to Python 3. The old codebase uses

import string

foo = string.replace(s, old, new)
foo = string.strip(s)
foo = string.find(s, sub, start, end)

I moved it with 2to3, but this gives an error. My guess is that I have to replace the above by

foo = s.replace(old, new)
foo = s.strip()
foo = s.find(sub, start, end)

I looked at the documentation:

They look exactly the same. Why were those functions in the string module in the first place? Was it a change before Python 2.7? Is there maybe a performance difference or some special cases which are treated differently?


Solution

  • Judging by the CPython 2.7 string module source, they are trivial wrappers for the method calls. This likely was different in a much older Python. From the initial comments of the same code:

    Beginning with Python 1.6, many of these functions are implemented as methods on the standard string object.