You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python替换字符串隔位/第N位单词为下划线 记忆项目实现问题

报错原因

你遇到的TypeError: 'str' object does not support item assignment报错由两个问题导致:

  • Python中的字符串是不可变对象,不支持直接通过下标赋值修改内部元素
  • 你直接对原字符串取下标,访问到的是单个字符,并不是拆分后的单词,无法按单词维度修改
实现方案

我们可以先把句子拆分为单词列表,按规则处理后再拼接回字符串,同时预留参数支持自定义保留单词的步长,满足扩展需求:

完整代码

# 获取用户输入
sentence = input('Please enter a sentence:\n\n')

def replace_unwanted_words(raw_sentence, keep_step=2):
    """
    按规则替换句子中的单词为下划线
    :param raw_sentence: 原始输入句子
    :param keep_step: 保留单词的间隔步长,默认值2表示每隔1个单词保留1个(保留第1、3、5...位单词);设置为3表示每隔2个单词保留1个(保留第1、4、7...位单词),以此类推
    :return: 处理后的句子
    """
    # 拆分句子为单词列表
    word_list = raw_sentence.split()
    processed_list = []
    for index, word in enumerate(word_list):
        # 按步长判断当前单词是否需要保留
        if (index + 1) % keep_step == 1:
            processed_list.append(word)
        else:
            # 下划线长度和原单词长度保持一致
            processed_list.append('_' * len(word))
    # 拼接回完整句子
    return ' '.join(processed_list)

使用示例

示例1:默认隔一个单词替换(保留第1、3、5...个单词)

result = replace_unwanted_words(sentence)
print(result)

输入:The quick brown fox jumped over the lazy dog.
输出:The _____ brown ___ jumped ____ the ____ dog.

示例2:仅保留每第3个单词

result = replace_unwanted_words(sentence, keep_step=3)
print(result)

输入:The quick brown fox jumped over the lazy dog.
输出:The _____ _____ fox ______ ____ the ____ ____

示例3:仅保留每第4个单词

传参keep_step=4即可实现。


内容的提问来源于stack exchange,提问作者TG Imagine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:24:03