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

Python字符串遍历清洗重构问题求助:现有代码待优化

代码问题分析与修正

原代码核心问题

  • 仅处理包含>或.的单词,其余无特殊符号的单词未输出,导致内容缺失
  • 独立的if判断可能引发重复处理,且未统一执行所有清洗规则
  • 逐个打印单词会破坏最终的连贯格式

修正后的代码

r = 'hello. with us today is >John Smith from c-n-n.'
processed_words = []
for word in r.split():
    # 移除>符号
    cleaned_word = word.replace('>', '')
    # 移除句点
    cleaned_word = cleaned_word.replace('.', '')
    # 处理连字符并转大写
    if '-' in cleaned_word:
        cleaned_word = cleaned_word.replace('-', '').upper()
    # 收集处理后的单词
    processed_words.append(cleaned_word)
# 拼接成最终字符串
result = ' '.join(processed_words)
print(result)

代码说明

  • 遍历所有拆分后的单词,每个单词都执行完整清洗流程,避免遗漏内容
  • 按固定顺序执行符号替换:先处理>,再处理.,最后处理连字符转大写
  • 用列表统一收集处理后的单词,最后用join拼接成连贯字符串,保证格式正确
  • 最终输出:hello with us today is John Smith from CNN

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:35:18