Rivers31334
Rivers31334

Reputation: 654

Printing to a single line

I am working on a python project and recently completed an assignment with a small exception. The final portion is to print a string, and for the life of me, it keeps printing on multiple lines.

I don't want to cheat in any way, but can somebody help me reach a solution where the final print is only to 1 line?

import random

def loadFile(fileName):
    file_variable = open(fileName, 'r')
    stringList = file_variable.readlines()
    file_variable.close()
    return stringList


def main():
    list_1 = loadFile('names.txt')
    list_2 = loadFile('titles.txt')
    list_3 = loadFile('descriptors.txt')

print(random.choice(list_2), random.choice(list_1), random.choice(list_1), ' the ', random.choice(list_3))

main()

Upvotes: 1

Views: 49

Answers (1)

falsetru
falsetru

Reputation: 369074

file.readlines() returns a list of lines which contains newlines. You need to strip the newline from the strings using str.strip or str.rstrip:

print(
    random.choice(list_2).rstrip(),  # rstrip('\n') if you want keep trailing space
    random.choice(list_1).rstrip(),
    random.choice(list_1).rstrip(),
    'the',
    random.choice(list_3).rstrip()
)

or by changing loadFile:

def loadFile(fileName):
    with open(fileName) as f:
        return [line.rstrip() for line in f]

Upvotes: 2

Related Questions