2024-06-26 14:11:15 发布
网友
我在上基础课。老师让我们创建一个程序,找到给定句子中的一个单词,然后打印出这个句子,在这个单词周围加上引号。现在,我可以让它查询一个句子,然后查询一个单词,它就会找到它。但是我如何让它用“猫”来代替“猫”这样的词呢?我正在调用找到的单词“occurrence”,但无法将其替换为“occurrence”。这是我尝试过的事情之一:
new_word = first.replace["(occurrence)", "(\", (occurrence), \")"]
replace是一个函数。要在Python中调用函数,需要使用syntacfunctionname(…)。您的代码使用functionname[…],即它使用方括号而不是括号
replace
functionname(…)
functionname[…]
The parameters are also not correct;修正了,代码是:
new_word = first.replace("(occurrence)", '"(occurrence)"']
但是,如果(occurrence)应该是一个变量,其中包含实际的问题单词,那么您需要更改代码。例如,您可以编写:
(occurrence)
new_word = first.replace(occurrence, '"' + occurrence + '"']
(根据您的Python版本,还有其他更好的编写方法,即使用f-strings;但是上面的方法可以工作。)
这将实现以下目的:
str = "occurrence1 occurrence2 occurrence3 occurrence1 occurrence4" print(str) new_str = str.replace('occurrence1 ', "'occurrence1'") print(new_str) # result = 'occurrence1' occurrence2 occurrence3 'occurrence1' occurrence4
replace
是一个函数。要在Python中调用函数,需要使用syntacfunctionname(…)
。您的代码使用functionname[…]
,即它使用方括号而不是括号The parameters are also not correct;修正了,代码是:
但是,如果
(occurrence)
应该是一个变量,其中包含实际的问题单词,那么您需要更改代码。例如,您可以编写:(根据您的Python版本,还有其他更好的编写方法,即使用f-strings;但是上面的方法可以工作。)
这将实现以下目的:
相关问题 更多 >
编程相关推荐