简体   繁体   English

字符串作为元组返回

[英]String is returned as a Tuple

I wrote a function in Python which returns should simple string based on 3 parameters, but it returns a tuple instead of a string.我在 Python 中写了一个 function ,它返回应该基于 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))

Output: Output:

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

Desired output:所需的 output:

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

The reason for this is that in python, if you use, to separate some values, it is interpreted as a tuple.原因是在 python 中,如果使用,来分隔某些值,则将其解释为元组。 So when you return, you are returning a tuple, not a string.所以当你返回时,你返回的是一个元组,而不是一个字符串。 You could either join the tuple, or use format strings like below.您可以加入元组,也可以使用如下格式字符串。

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

You can do it using join您可以使用加入来做到这一点

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(' '.join(my_TAs(test_first_TA, test_second_TA, test_third_TA)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM