【问题标题】:One print statement two variables get printed on two different lines一个打印语句两个变量打印在两个不同的行上
【发布时间】:2020-03-19 18:54:11
【问题描述】:
with open("C:\\Users\\Nav\\Desktop\\script\\names.txt", 'r+') as f:
    for x in range (0, 100):
        f_contents = f.readline()
        name = f_contents
        name2 = name
        print(name.lower().replace(" ", "") + "@gmail.com" + "\n")

x = input()

使用此代码,我正在尝试读取每行带有全名的文件并对其进行格式化,效果很好,但是当我添加“@gmail.com”并将其打印出来时,它会打印到两个不同的控制台中的行。

例如,我的输出是

austenrush
@gmail.com

yuvaanduncan
@gmail.com

jawadpatton
@gmail.com

hanifarusso
@gmail.com

kerysbeck
@gmail.com

safiyamcguire
@gmail.com

oluwatobilobamiddleton
@gmail.com

虽然我想得到:

austenrush@gmail.com

yuvaanduncan@gmail.com

jawadpatton@gmail.com

hanifarusso@gmail.com

kerysbeck@gmail.com

safiyamcguire@gmail.com

oluwatobilobamiddleton@gmail.com

【问题讨论】:

    标签: python python-3.x email generator


    【解决方案1】:

    readline 不会删除从文件中读取的换行符;你必须自己做。

        f_contents = f.readline().rstrip("\n")
    

    不过,文件是可迭代的,因此您无需显式调用 readline

    from itertools import islice
    
    
    with open("C:\\Users\\Nav\\Desktop\\script\\names.txt", 'r+') as f:
        for f_contents in islice(f, 100):
            name = f_contents.rstrip("\n").lower().replace(" ", "")
            print(name + "@gmail.com" + "\n")
    
    x = input()
    

    【讨论】:

    • 使用您的代码时出现错误异常发生:ValueError too many values to unpack (expected 2) File "C:\Users\Nav\Desktop\script\start.py",第 6 行, in for _, f_contents in islice(f, 100):
    • 对不起,我本来打算用enumerate,才决定用islice,忘了更新目标变量。那应该只是for f_contents in ...
    猜你喜欢
    • 2022-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    • 2011-05-22
    • 2017-12-12
    • 2014-06-09
    • 1970-01-01
    相关资源
    最近更新 更多