Python的字符串连接问题

时间:2017-02-22 03:46:24

标签: python python-3.x

此计划的目标是从文件中读取学生姓名列表,为这些学生生成电子邮件,然后将这些电子邮件保存到外部文本文件中。我写了一个能够正确生成电子邮件的函数。但是,当我在generateEmail函数中调用newStudentEmail时,它会从通用文本文件中读取这些名称。我遇到的问题是在domainfirstInitial之前添加了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()

1 个答案:

答案 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:])包含换行符时,返回lastNameemail并且上面输入的整个输出是

'asmith\n@college.edu'