Printing line between variables, how do I stop this? [duplicate]

久未见 提交于 2020-01-25 10:12:09

问题


Python code outputs a new line between first name, last name and email address, how can I stop this from happening? e.g.

ogchu
@gmail.com
ogchu
@yahoo.com
ogchu
@hotmail.com
ogchu
@aol.com
ogchu
@bigpond.com

The first.txt and last.txt files have about 2,000 and 100 names respectively, so manually going through and doing stuff isn't really an option.

The aim of the code is to try and generate authentic looking email adresses, sometimes with a firstname and lastname, other times with 1 initial and a lastname, and other times with 2 initials and a lastname.

Code:

import random
import string
import time

count = 0
while count < 50:
    x = random.randint(0, 1)
    y = random.randint(0, 1)
    z = random.randint(0, 1)
    if x == 0:
        prefix1 = random.choice(string.ascii_lowercase)
        prefix2 = random.choice(string.ascii_lowercase)
        first = ""
    if x == 1:
        prefix1 = random.choice(string.ascii_lowercase)
        prefix2 = ""
        first = ""
    if x == 1 and y == 1:
        prefix1 = ""
        prefix2 = ""
        first = random.choice(open('first.txt').readlines())

    last = random.choice(open('last.txt').readlines())

    print(prefix1 + prefix2 + first + last + "@gmail.com")
    print(prefix1 + prefix2 + first + last + "@yahoo.com")
    print(prefix1 + prefix2 + first + last + "@hotmail.com")
    print(prefix1 + prefix2 + first + last + "@aol.com")
    print(prefix1 + prefix2 + first + last + "@bigpond.com")
    print(prefix1 + prefix2 + first + last + "@icloud.com")
    print(prefix1 + prefix2 + first + last + "@outlook.com")
    count = count + 1
    time.sleep(3)

回答1:


The problem is in

first = random.choice(open('first.txt').readlines())

and

last = random.choice(open('last.txt').readlines())

When you read a line, the last character is \n(newline). You need to remove it by calling .strip() method like:

last = last.strip()
first= first.strip()


来源:https://stackoverflow.com/questions/59783391/printing-line-between-variables-how-do-i-stop-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!