I think your confusion here (and most of the answers) is different from the string module and the str built-in class. These are completely different things, even if there are many overlaps in functionality.
string.replace(s, old, new) is a free function, not a method. You cannot call it like s.replace(old, new) , because s cannot be an instance of the string module.
str.replace(self, old, new) - method. Like any other method (except for the classmethod and staticmethod methods), you can and usually execute it through a str instance, like s.replace(old, new) , where s automatically becomes a self parameter.
You can also call the method through the class, so str.replace(s, old, new) turns out to be exactly the same as s.replace(old, new) . And it so happened that if s is str , it does the same as string.replace(old, new) . But this is indeed a coincidence, true for historical reasons.
As a note, you almost never want to call functions in the string module. They are mostly a delay from very early versions of Python. In fact, string.replace is listed in the "Deprecated String Functions" section of the documentation, like most other functions that you probably looked for there. The reason the whole module is not deprecated is because it has some things that do not belong to the str class (either bytes or unicode ), for example, constants like string.digits .
source share