本文介绍了替换字符串中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,挑战在于用星号替换句子中的特定单词,其长度等于该单词的长度-3个字母-> 3个星号,等等.
So the challenge was to replace a specific word in a sentence with asterisks with equivalent length to that word - 3 letters --> 3 asterisks etc.
第一节不起作用,但是第二节却可以-有人可以批评第一节,也许指出我可能犯的错误,因为逻辑本来听起来很合理?
Section One does not work, but Section Two does - can anyone critique Section One and maybe point out the possible mistake I was making, as the logic seemed sound originally?
def censor(text, word):
for c in text:
if c == word: ## this line was totally wrong
text.replace(c, "*" * len(c))
return text
下一段工作了,然后CodeAcademy的答案就大不相同了:
The next segment does work, then CodeAcademy's answer was way different:
def censor(text, word):
a = "*" * len(word)
for c in text:
nw = text.split(word)
return a.join(nw)
您将如何处理此任务?
How would you approach this task?
推荐答案
第二种解决方案也不完美:
The second solution is not perfect either:
def censor(text, word):
a = "*" * len(word)
nw = text.split(word) # no need for a loop here, one split catches all occurrences
return a.join(nw)
第一次尝试:
def censor(text, word):
# for c in text: # loops char by char
# if c == word: # one character likely won't be your word
# text.replace(c, "*" * len(c)) # does nothing, string is immutable
return text.replace(word, "*" * len(word)) # simple!
这篇关于替换字符串中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!