man
man

Reputation: 173

Trying to print multiple variable under loop

Here is what I tried

f = open('names.txt')
for people in f:
    print('{0} and {1}'.format(people, people))

Output:

john
and john

vlad 
and vlad

But my expected output is

john and john
vlad and vlad

What is wrong here and how to fix it?

Upvotes: 1

Views: 49

Answers (2)

Richard Nemeth
Richard Nemeth

Reputation: 1864

You can try removing the newline characters:

f = open('names.txt')
for people in f:
    people = people.replace("\n", "")
    print('{0} and {1}'.format(people, people))

This way there should only be a new line on the next person in the file f.

Upvotes: 2

davejagoda
davejagoda

Reputation: 2528

How about this:

people = people.rstrip()
print('{0} and {1}'.format(people, people))

Upvotes: 3

Related Questions