当前位置: 代码迷 >> python >> 如何用用户输入的单词替换用户输入的句子。 str对象不可调用
  详细解决方案

如何用用户输入的单词替换用户输入的句子。 str对象不可调用

热度:102   发布时间:2023-06-19 09:22:40.0
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)

我已经知道了,但是当我运行它时说

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

您需要: n_s = sentence.replace(change, replace) 它给您一个类型错误,因为名为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)

#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

方法replace()返回字符串的副本,在该字符串中,已出现的旧内容已被新内容替换,可以选择将替换次数限制为最大。

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

  • old-这是要替换的旧子字符串。
  • new-这是新的子字符串,它将替换旧的子字符串。
  • max-如果给出此可选参数max,则仅替换第一个出现的次数。

这是针对python 3的更正代码。请注意,print语句之前的最后一行的语法为n_s = statement.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)
  相关解决方案