用python处理列表和消息

2024-06-25 23:18:44 发布

您现在位置:Python中文网/ 问答频道 /正文

这里很新,但我要邀请3个人来吃饭,我得从邀请他们吃饭的名单上给他们每人发一条信息。。我才刚开始

dinnerGuest = ['Steve Jobs', 'Tupac Shakur', 'Kobe Bryant']
message = """You have been cordially invited to an epic dinner.
Please RSVP as soon as possible. Thank you""" + dinnerGuest[0].title + "."
print(message)

我得到了错误

Please RSVP as soon as possible. Thank you""" + dinnerGuest[0].title + "."
TypeError: Can't convert 'builtin_function_or_method' object to str implicitly

有人知道为什么吗?提前谢谢,我知道这是一个新手问题。不过我会到那里的。你知道吗


Tags: toyou信息messagetitleasjobssteve
2条回答
dinnerGuest = ['Steve Jobs', 'Tupac Shakur', 'Kobe Bryant']
message = """You have been cordially invited to an epic dinner.
Please RSVP as soon as possible. Thank you""" + dinnerGuest[0].title() + "."
print(message)

title()是一个函数-它接受某个对象并将其转换为其他对象。你知道吗

无论何时使用函数,都要在末尾加括号。你知道吗

由于要邀请列表中的所有来宾,因此必须使用循环遍历整个列表:

dinnerGuest = ['Steve Jobs', 'Tupac Shakur', 'Kobe Bryant']

message = """You have been cordially invited to an epic dinner. 
              Please RSVP as soon as possible. Thank you """

for i in dinnerGuest:
    print(message + i.title() + ".")

同样正如@Andrew Owen和@Francisco Couzo所提到的,您需要使用title()而不是title,因为它是一个方法,需要在它后面加上()。你知道吗

相关问题 更多 >