Skip to content Skip to sidebar Skip to footer

How To Use .replace In Python?

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

Solution 1:

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!

Solution 2:

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...

Solution 3:

Try This

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

Solution 4:

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:

defreplaceWord(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.

Post a Comment for "How To Use .replace In Python?"