首页 > 解决方案 > 字符串作为元组返回

问题描述

我在 Python 中编写了一个函数,它返回基于 3 个参数的简单字符串,但它返回一个元组而不是一个字符串。

def my_TAs(test_first_TA, test_second_TA, test_third_TA):

    return test_first_TA, test_second_TA, "and", test_third_TA, "are awesome!."

test_first_TA = "Joshua"

test_second_TA = "Jackie"

test_third_TA = "Marguerite"

print(my_TAs(test_first_TA, test_second_TA, test_third_TA))

输出:

('Joshua', 'Jackie', 'and', 'Marguerite', 'are awesome!')

期望的输出:

"Joshua, Jackie, and Marguerite are awesome!".

标签: pythonstringfunctionreturntuples

解决方案


这样做的原因是,在 python 中,如果你使用 , 来分隔一些值,它会被解释为一个元组。所以当你返回时,你返回的是一个元组,而不是一个字符串。您可以加入元组,也可以使用如下格式字符串。

return f'{test_first_TA}, {test_second_TA}, and {test_third_TA} are awesome!'

推荐阅读