[英]how to fix: “list indices must be integers or slices, not str”
im new to python, still learning it and im trying to make a script that sends out emails to multiple emails but im having a problem with it.我是 python 的新手,仍在学习它,我正在尝试制作一个将电子邮件发送到多封电子邮件的脚本,但我遇到了问题。 it keeps on printing out an error in line 9:它继续在第 9 行打印出错误:
"list indices must be integers or slices, not str" “列表索引必须是整数或切片,而不是 str”
and im confused on what that means and what i need to do to fix that.我对这意味着什么以及我需要做些什么来解决这个问题感到困惑。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
email_list = ["First@email.com", "second@email.com", "third@email.com", "etc..."]
num = 0
for i in email_list:
msg['To'] = email_list[i] #this line gives the error
num = num + 1
server.sendmail(email, email_list[i], text)
print("Emails Sent: " + num)
I expect the output to be, Emails Sent: 3, but it doesn't lol我希望 output 是,已发送电子邮件:3,但它不会大声笑
In python for e in collections
must be read as 'for each element e of the collection', meaning that e
takes the value of each element in the collection.在 python for e in collections
必须读作“对于集合的每个元素 e”,这意味着e
取集合中每个元素的值。
In your example, i
will take the values "First@email.com" then "second@email.com" etc.. and not 0, 1... as you seem to believe.在您的示例中, i
将采用“First@email.com”然后“second@email.com”等值,而不是您似乎相信的 0、1...。 However when you're doing email_list[i]
you're trying to get the i'th value of your list.但是,当您执行email_list[i]
时,您正在尝试获取列表的第 i 个值。 Which cannot works since we saw that i
is a string.因为我们看到i
是一个字符串,所以它不能工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.