问题
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