错误的程序审查(Codecademy网站)熟能生巧
问题描述:
我想包括空间的同时也分割文本,对于我抬头对谷歌使用的进口重新错误的程序审查(Codecademy网站)熟能生巧
import re
def censor(text,word) :
text1=re.split(r"(\s+)",text)
#print text1
sum=""
for i in range(0,len(text1)) :
if text1[i]==word :
for j in range(0,len(word)) :
sum=sum+"*"
else :
sum=sum+text[i]
return sum
我得到的错误是
image displaying error and code
如果我包含另一个for循环来替换每个'e'与空白,它不起作用。
答
在你的代码中,text1
(很坏的命名BTW)是一个单词列表,而text
单个字符串。您的第一个for
循环正在迭代text1
索引(列表中的词),但是在else
子句中,您会对整个text
字符串下标。显然,您想从单词列表(text1
)中获取单词,而不是text
字符串中位置为i
的字符。 IOW:将else
条款替换为:
sum=sum+text1[i]
并且测试应通过。
如果你使用你肯定会更容易发现问题的一个正确的命名和适当的代码布局:多
def censor(text, word) :
words = re.split(r"(\s+)",text)
sum=""
for i in range(0, len(words)) :
if words[i] == word :
for j in range(0, len(word)) :
sum = sum + "*"
else :
# here you easily spot the error
sum = sum + text[i]
return sum
你也使事情复杂得多,他们必须。你可以在循环之前为所有的“坏”字预先计算“替换”字符串(并且你不需要循环来完成),并且你不需要一个range
和索引访问,你可以迭代直接在单词列表上:
def censor(text, word) :
replacement = "*" * len(word)
words = re.split(r"(\s+)", text)
cleaned = ""
for w in words :
if w == word :
cleaned += replacement
else :
cleaned += w
return cleaned
会有其他可能的改进,但至少这是大多数可读性和更pythonic。