Zakariya Islam
Zakariya Islam

Reputation: 21

How do I replace a user entered sentence with a user entered word. str object not callable

sentence = input ('Please enter a sentce: ')
change = input ('What word do you want to change: ')
replace = input ('What do you want to replace it with: ')
n_s = replace(change,replace)
print (n_s)

I've got this but when I run it it says

n_s = replace(change,replace) TypeError:'str' object is not callable

Upvotes: 0

Views: 60

Answers (3)

DrM
DrM

Reputation: 2525

Here is the corrected code, for python 3. Notice that the syntax for the last line before the print statement is n_s = sentence.replace(change,replace)

sentence = input ('Please enter a sentce: ')
change = input ('What word do you want to change: ')
replace = input ('What do you want to replace it with: ')
n_s = sentence.replace(change,replace)
print (n_s)

Upvotes: 0

Chandu
Chandu

Reputation: 2129

sentence = input ('Please enter a sentce: ')
change = input ('What word do you want to change: ')
replace = input ('What do you want to replace it with: ')
n_s = sentence.replace(change,replace)
print(n_s)

#output:
Please enter a sentce: hello world bye
What word do you want to change: bye
What do you want to replace it with: bye-bye
hello world bye-bye

The method replace() returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max.

Syntax: str.replace(old, new[, max])

  • old − This is old substring to be replaced.
  • new − This is new substring, which would replace old substring.
  • max − If this optional argument max is given, only the first count occurrences are replaced.

Upvotes: 1

MalloyDelacroix
MalloyDelacroix

Reputation: 2293

You want: n_s = sentence.replace(change, replace). It is giving you a type error because your variable named replace is a string and you are trying to call it like a method.

Upvotes: 2

Related Questions