如何用引号将出现的单词括起来?

2024-06-26 14:11:15 发布

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

我在上基础课。老师让我们创建一个程序,找到给定句子中的一个单词,然后打印出这个句子,在这个单词周围加上引号。现在,我可以让它查询一个句子,然后查询一个单词,它就会找到它。但是我如何让它用“猫”来代替“猫”这样的词呢?我正在调用找到的单词“occurrence”,但无法将其替换为“occurrence”。这是我尝试过的事情之一:

new_word = first.replace["(occurrence)", "(\", (occurrence), \")"]

Tags: 程序new老师单词事情replace引号句子
2条回答

replace是一个函数。要在Python中调用函数,需要使用syntacfunctionname(…)。您的代码使用functionname[…],即它使用方括号而不是括号

The parameters are also not correct;修正了,代码是:

new_word = first.replace("(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

相关问题 更多 >