1

Here is a string in python:

a = "asdf as df adsf as df asdf asd f"

Lets say that I want to replace all " " with "||", so I do:

>>> a.replace(" ", "||")
'asdf||as||df||adsf||as||df||asdf||asd||f'

My confusion is info from the documentation as below:

 string.replace(s, old, new[, maxreplace])
    Return a copy of string s with all occurrences...

I can "omit" s, but based on the documentation I need s; however, I only provide old, and new. I noticed that it's like this with a lot of the python documentation; what am I missing?

3 Answers 3

5

You are mixing up str object methods with the string module functions.

The documentation you are referring to is the string module documentation. Indeed, there is a function in the string module called replace which takes 3 (or optionally, 4) arguments:

In [9]: string
Out[9]: <module 'string' from '/usr/lib/python2.7/string.pyc'>

In [11]: string.replace(a, ' ', '||')
Out[11]: 'asdf||as||df||adsf||as||df||asdf||asd||f'

a is a str object -- (str is a type, string is a module):

In [15]: type(a)
Out[15]: str

And str objects have a replace method. The documentation for the str methods is here.

Sign up to request clarification or add additional context in comments.

3 Comments

I would add that the string module should not be used since most of its functionalities have been merged with the str string class, +1
@StefanoSanfilippo: There are some string functions which are deprecated, like string.atof, but the whole module is not deprecated. The functions can be useful when you need the function, not the method bound to a particular str, and the constants are useful too.
Yeah, I reworded the comment shortly after with should not be used. What I said is in the first paragraph of the string module docs. As of "free functions", you could just use str.upper and the like (e.g. map(str.upper, ["a", "b"])).
1

The first parameter of a method is a reference to the object (usually called self) being modified and is implicitly passed when you use the object.method(...) notation. So this:

a = "asdf as df adsf as df asdf asd f"
print a.replace(" ", "||")

is equivalent to this:

a = "asdf as df adsf as df asdf asd f"
print str.replace(a, " ", "||")

str being the class of the a object. It's just syntactical sugar.

Comments

1

When you call a method of an object, the object is supplied automatically as the first parameter. Generally within the method this is referred to as self.

So you can call the function passing in the object:

string.replace(s, old, new)

or you can call the method of the object:

s.replace(old, new)

Both are functionally identical.

1 Comment

It's str, not string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.