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

Python编写pig_latin函数仅返回字符串最后部分,该如何修复?

问题修复方案

根因分析

代码仅返回输入字符串最后部分转换结果的核心原因是:循环中每次都覆盖了存储转换结果的变量,没有累积保存所有单词的转换内容,最终返回值只保留了最后一个单词的转换结果。同时"".join(x)属于冗余写法,x本身已经是拼接完成的单个字符串,无需调用join方法处理。

修正后代码

def pig_latin(text):  
    say = "ay"
    words = text.split()
    converted_words = []
    for word in words:
        converted_word = word[1:] + word[:1] + say
        converted_words.append(converted_word)
    return " ".join(converted_words)

print(pig_latin("hello how are you"))

运行上述代码输出结果为:ellohay owhay reaay ouyay,符合Pig Latin的转换规则。

修改点说明

  • 新增空列表converted_words,用来逐个存储每个单词的转换结果
  • 循环内将每个转换完成的单词追加到列表中,避免覆盖之前的转换结果
  • 循环结束后用" ".join(converted_words)将所有转换后的单词用空格拼接为完整字符串后返回

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:36:03