Following the Python documentation for string.replace ( http://docs.python.org/library/string.html ):
string.replace(str, old, new[, maxreplace])
Return a copy of string str with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.
Using the format as given generates the following error:
>>> a = 'grateful'
>>> a.replace(a,'t','c')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
It seems odd that you’d need the "str" repeated and from the error I guessed that my third argument was being taken for maxreplace.
The format:
string.replace(old, new)
does seem to function as expected.
I’m wondering if I am misunderstanding something, and the form given in the Python documentation is, in fact, correct in some way.
I think your confusion here (and that of most of the answers) is the different between the
stringmodule and thestrbuilt-in class. They’re entirely separate things, even if there is a lot of overlap in functionality.string.replace(s, old, new)is a free function, not a method. There’s no way you can call it ass.replace(old, new), becausescannot be an instance of thestringmodule.str.replace(self, old, new)is a method. As with any other method (other than classmethod and staticmethod methods), you can—and usually do—call it through astrinstance, ass.replace(old, new), wheresbecomes theselfparameter automatically.You can also call a method through the class, so
str.replace(s, old, new)turns out to be exactly the same ass.replace(old, new). And it just so happens that, ifsis astr, this does the exact same thing asstring.replace(old, new). But that’s really a coincidence that’s true for historical reasons.As a side note, you almost never want to call functions in the
stringmodule. They’re mostly a holdover from very early versions of Python. In fact,string.replaceis listed under the “Deprecated string functions” section in the documentation, as are most of the other functions you’d probably go looking for there. The reason the whole module hasn’t been deprecated is that it has some things that don’t belong in thestr(orbytesorunicode) class, such as constants likestring.digits.