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
相关产品推荐
相关产品推荐

