0

I want to replace a word in a string with another word. Ex. replaceWord("cool","awesome","Stack overflow is cool.") Output would be: "Stack overflow is awesome" I don't understand why my code isn't working.

def replaceWord(oldWord,newWord,aStr):
    aStr.replace(oldWord,newWord)
    return aStr
2

4 Answers 4

7
def replaceWord(old, new, astr):
   return astr.replace(old, new)

A string operation is never in-place - instead replace() will create a new string because strings are immutable.

But wait...why do you want your own string replaceWord() method?

Strings have their own build-in replace() method!

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

2 Comments

Of course, it's preferred to just use str.replace as opposed to wrapping it like this.
Nah. I'm an intro CS student, so I always have dumb questions like this. Thanks though!
1

Why are you not just using the return value of aStr.replace(oldWord,newWord)? Why is it necessary to nest this function inside another function? As for your question it is because replace is not an in place operation. You need to do something like:

return aStr.replace(oldWord, newWord)

Anyways I still find it strange that you wrapped it in a function...

Comments

1

Try This

def replaceWord(oldWord,newWord,aStr): 
   aStr = aStr.replace(oldWord,newWord) 
   return aStr

Comments

1

As per http://docs.python.org/2/library/string.html

string.replace(s, old, new[, maxreplace]) Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

Your code should thus be modified to:

def replaceWord(oldWord,newWord,aStr):
    return aStr.replace(oldWord,newWord)

This difference being that yours did not catch the returned (new) string from the replace function.

Ideally thought you should just use aStr.replace(oldWord,newWord) without wrapping it in a function. There would be less overhead that way, and it makes the code clearer.

If you want it to only replace the first word you can add the third, optional, parameter which is the number of replacements to do.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.