Python代码问题:替换句子中每第三个单词的字母为#失效
问题:替换句子中每第三个单词的字母为#符号
需求
找出句子中的每第三个单词,仅将该单词中的字母替换为#符号。
我的代码
def redact_words(sentence): redacted_sentence = sentence.split() for word in redacted_sentence[2::3]: for i in word: if i.isalpha(): word.replace(i, '#') else: continue return " ".join(redacted_sentence)
测试示例
- 输入:
sentence = "You cannot drink the word 'water'." - 期望输出:
"You cannot ##### the word '#####'." - 实际输出:与输入完全一致,无任何替换效果
问题原因及修复
核心问题
- 字符串不可变性:Python中字符串是不可变对象,
word.replace(i, '#')不会修改原word,而是返回新字符串,你没有将新字符串赋值回原列表的对应位置。 - 遍历方式无效:直接遍历
redacted_sentence[2::3]得到的是列表元素的副本,修改副本不会影响原列表中的元素。
修正后的代码
def redact_words(sentence): words = sentence.split() # 遍历每第三个单词的索引(从第3个单词开始,步长3) for idx in range(2, len(words), 3): word = words[idx] # 替换字母为#,非字母字符保留 redacted_word = ''.join(['#' if c.isalpha() else c for c in word]) # 更新原列表对应位置的单词 words[idx] = redacted_word return " ".join(words)
代码说明
- 通过索引遍历原列表,直接修改列表内的元素,确保修改生效。
- 用列表推导式快速生成替换后的单词:逐个检查字符,字母替换为
#,非字母原样保留。 - 将处理后的单词重新赋值给列表对应索引,保证最终拼接的是修改后的内容。
验证结果
运行修正后的代码,输入示例将输出符合预期的结果:"You cannot ##### the word '#####'."
内容的提问来源于stack exchange,提问作者Thabo Thandekiso
相关产品推荐
相关产品推荐

