Python编写my_TAs函数多变量字符串拼接返回结果异常求助
问题原因
- 现有函数仅使用了第一个入参
first_TA拼接字符串,未使用second_TA、third_TA两个参数 - 你之前尝试的逗号分隔写法,在Python中会生成元组而非完成字符串拼接,同时缺少要求格式里的逗号、空格、
and等固定连接字符
正确代码实现
推荐使用Python f-string实现,格式清晰不易出错:
def my_TAs(first_TA, second_TA, third_TA): result = f"{first_TA}, {second_TA}, and {third_TA} are awesome!" return result # 测试用例不需要修改 test_first_TA = "Joshua" test_second_TA = "Jackie" test_third_TA = "Marguerite" print(my_TAs(test_first_TA, test_second_TA, test_third_TA))
如果你更习惯用+做字符串拼接,也可以写成如下形式,效果完全一致:
def my_TAs(first_TA, second_TA, third_TA): result = str(first_TA) + ", " + str(second_TA) + ", and " + str(third_TA) + " are awesome!" return result
运行结果
执行测试代码后会输出符合要求的结果:Joshua, Jackie, and Marguerite are awesome!
内容的提问来源于stack exchange,提问作者GeekMaster17
相关产品推荐
相关产品推荐

