0

I am trying to make a name generator. I am using F string to concatenate the first and the last names. But instead of getting them together, I am getting them in a new line.

print(f"Random Name Generated is:\n{random.choice(firstname_list)}{random.choice(surname_list)}")

This give the output as:

    Random Name Generated is:
Yung 
heady

Instead of:

Random Name Generated is:

Yung heady

enter image description here

Can someone please explain why so?

2 Answers2

0

The code seems right, perhaps could be of newlines (\n) characters in element of list. Check the strings of lists.

import random

if __name__ == '__main__':
      firstname_list = ["yung1", "yung2", "yung3"]
      surname_list = ["heady1", "heady2", "heady3"]
      firstname_list = [name.replace('\n', '') for name in firstname_list] 
      print(f"Random Name Generated is:\n{random.choice(firstname_list)} {random.choice(surname_list)}")

Output:

Random Name Generated is:
yung3 heady2
Code123
  • 49
  • 3
  • 1
    Indeed there were. As I had pulled the values from a UTF-8 encoded .txt file, there were newlines within the elements of the list themselves. I used .strip() to resolve this problem. print(f"Random Name Generated is:\n{random.choice(firstname_list).strip()} {random.choice(surname_list).strip()}") – Jayit Ghosh Apr 10 '21 at 12:18
0

Since I had pulled these values from UTF-8 encoded .txt file, the readlines() did convert the names to list elements but they had a hidden '\xa0\n' in it.

This caused this particular printing problem. Using .strip() helped to remove the spaces.

print(f"Random Name Generated is:\n{random.choice(firstname_list).strip()} {random.choice(surname_list).strip()}")