Python 类型错误:无法连接电子邮件中的“str”和“list”对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26521899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:35:43  来源:igfitidea点击:

TypeError: cannot concatenate 'str' and 'list' objects in email

python

提问by Enzo Vidal

I am working on sending an email in python. Right now, I want to send entries from a list via email but I am encountering an error saying "TypeError: cannot concatenate 'str' and 'list' objects" and I have no idea to debug it. The following is the code that I have. I'm still new in this language (3 weeks) so I have a little backgroud.

我正在用 python 发送电子邮件。现在,我想通过电子邮件发送列表中的条目,但遇到一个错误,提示“TypeError:无法连接 'str' 和 'list' 对象”,我不知道要调试它。以下是我拥有的代码。我还是这门语言的新手(3 周),所以我有一点背景。

import smtplib
x = [2, 3, 4] #list that I want to send
to = '' #Recipient
user_name = '' #Sender username
user_pwrd = '' #Sender Password
smtpserver = smtplib.SMTP("mail.sample.com",port)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login(user_name,user_pwrd)

#Header Part of the Email       
header = 'To: '+to+'\n'+'From: '+user_name+'\n'+'Subject: \n'
print header

#Msg 
msg = header + x #THIS IS THE PART THAT I WANT TO INSERT THE LIST THAT I WANT TO SEND. the type error occurs in this line

#Send Email     
smtpserver.sendmail(user_name, to, msg)
print 'done!'

#Close Email Connection
smtpserver.close()

采纳答案by David Sanders

The problem is with msg = header + x. You're trying to apply the +operator to a string and a list.

问题在于msg = header + x. 您正在尝试将+运算符应用于字符串和列表。

I'm not exactly sure how you want xto be displayed but, if you want something like "[1, 2, 3]", you would need:

我不确定您希望如何x显示,但是,如果您想要“[1, 2, 3]”之类的内容,则需要:

msg = header + str(x)

Or you could do,

或者你可以这样做

msg = '{header}{lst}'.format(header=header, lst=x)

回答by Irshad Bhat

Problem is that in the code line msg = header + x, the name headeris a string and xis a list so these two cannot be concatenated using +operator. The solution is to convert xto a string. One way of doing that is to extract elementsfrom the list, convertthem to strand .join()them together. So you should replace the code line:

问题是在代码行中msg = header + x,名称header是一个字符串并且x是一个列表,因此这两个不能使用+运算符连接。解决方案是转换x为字符串。这样做的一种方式是提取元素list转换他们str.join()他们在一起。所以你应该替换代码行:

msg = header + x

by:

经过:

msg = header + "".join([str(i) for i in x])