此计划的目标是从文件中读取学生姓名列表,为这些学生生成电子邮件,然后将这些电子邮件保存到外部文本文件中。我写了一个能够正确生成电子邮件的函数。但是,当我在generateEmail
函数中调用newStudentEmail
时,它会从通用文本文件中读取这些名称。我遇到的问题是在domain
和firstInitial
之前添加了lastName
(@ college.edu)。
例如,名字Georgene,Montezuma将返回@ college.edugmontezuma
我尝试在for循环中连接domain
并出现同样的问题。有没有人解释为什么会这样?
def generateEmail(name):
#Generates an email address given a first and last name separated by a comma
firstInitial = str.lower(name[0])
comma = name.find(",")
lastName = str.lower(name[comma+1:])
domain = "@college.edu"
email = firstInitial + lastName + domain
return email
def newStudentEmail():
file = open("newStudents.txt", "r")
header = next(file)
for name in file:
newEmail = print(generateEmail(name),end="")
#outfile = open("newStudentsEmail.txt", "a")
#outfile.write(newEmail)
file.close()
#outfile.close()
答案 0 :(得分:0)
原因如下:每生成name
后都会出现换行符。
快速解决方法是将lastName = str.lower(name[comma+1:])
更改为lastName = str.lower(name[comma+1:-1])
或者使用name.strip()
作为布兰登在评论中说。
我已运行您的代码,并使用以下文本作为newStudentsEmail.txt
header line
Alan,Smith
Bob,Lee
在行for name in file
中,name
字符串包含换行符。传递给name
的{{1}}变量是“Alan,Smith \ n”,当generateEmail
lastName = str.lower(name[comma+1:])
包含换行符时,返回lastName
是email
并且上面输入的整个输出是
'asmith\n@college.edu'