0

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)
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 2
    `... + last.strip() + ...`? You're reading those names from a file, the lines have trailing newlines. – jonrsharpe Jan 17 '20 at 08:12
  • @jonrsharpe so do i need to just remove the newline from every line in both the files? can i write a program to do that for me? – Jensen Lloyd Jan 17 '20 at 08:15
  • 1
    @jonrsharpe: I have reopened it (even before reading your comment :-) ) – Serge Ballesta Jan 17 '20 at 08:16
  • If you removed the newlines from the files, how would that help? Yes it's possible to write a program to do that, but then you'd read one single line with all of the names mashed together. Just do what I suggested above, remove the newline from the chosen value using the strip method. – jonrsharpe Jan 17 '20 at 08:17

1 Answers1

2

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()
Ajay Dabas
  • 1,404
  • 1
  • 5
  • 15
matevzpoljanc
  • 211
  • 2
  • 11