Python中的不同审查脚本

Python中的不同审查脚本,python,Python,我试图弄明白为什么我的代码的一个版本可以工作,而另一个版本不能 任务的目标是创建一个名为censor的函数,该函数接受两个字符串(文本和单词)作为输入。它应该返回文本,并用星号替换您选择的单词 这是我写的第一段代码,但它不起作用 def censor(text, word): import string text = string.split(text) for index in range(0, len(text)): if word == text[index]

我试图弄明白为什么我的代码的一个版本可以工作,而另一个版本不能

任务的目标是创建一个名为censor的函数,该函数接受两个字符串(文本和单词)作为输入。它应该返回文本,并用星号替换您选择的单词

这是我写的第一段代码,但它不起作用

def censor(text, word):

  import string 

  text = string.split(text)

  for index in range(0, len(text)):
     if word == text[index]:
        text[index] = len(word) * '*'

  text = string.join(text)
  return text
上述代码段返回了一个错误:

Oops, try again. Your function fails on censor("hey hey hey","hey"). It returns "* * * h e y h e y" when it should return "*** *** ***".
下面是第二段代码,它确实有效

def censor(text, word):

    import string 

    text = string.split(text)

    for index in range(0, len(text)):
        if text[index] == word:
            text[index] = "*" * len(word)

    return " ".join(text)
我不明白为什么text=string.jointext不起作用,而.jointext起作用

读取string.join。应该对要连接文本的字符串调用join。比如说,

>>> ', '.join(['a', 'b', 'c']
'a, b, c'

使用正则表达式可以更轻松地执行此操作:

import re
def censor(text, word):
    return re.sub(r'\b' + word + r'\b', '*', text)

这并没有回答以下问题:为什么第一个函数不能工作?您正在运行哪个版本的Python?string.joinlist在版本2.x中已被弃用,将在3.x.1中删除。不要将列表拆分的结果分配回文本。使用不同的变量名。2不要使用索引进行迭代。python的方式是listOfWords中的w:。3不要将连接字符串的结果指定给文本。使用不同的变量名。对于Barmar,我在web上使用Codecademy,所以我不确定他们使用的是哪个版本的Python。知道他们已弃用string.joinlist并在以后将其删除会有所帮助。谢谢非常感谢。这对我来说很有意义。我想当我阅读string.join上的文档时,我需要键入string.join,而不是我想要加入的字符串。这很有帮助!