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

2024-09-30 01:36:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: toyouinputwithitchangedowhat
3条回答
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,则只替换第一次计数。你知道吗

下面是针对python3的更正代码。请注意,print语句前面最后一行的语法是n\u s=句子.替换(更换)

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)

你想要:n_s = sentence.replace(change, replace)。它会给您一个类型错误,因为名为replace的变量是一个字符串,您试图像方法一样调用它。你知道吗

相关问题 更多 >

    热门问题