qwdwdqqww
qwdwdqqww

Reputation: 9

How to print items from two lists on the same line?

Really new to python, started today. I got a list of verbs and nouns from a txt list, I loaded them in and I was trying to print a noun and verb together from a specific position in the list. How do I make them print on the same line? they were printed on different lines.

Here is my code:

    f = open('/User/Desktop/Python/nouns/2syllablenouns.txt', 'r')
nouns = []
for l in f:
    nouns.append(l)

f = open('/User/Desktop/Python/verbs/2syllableverbs.txt', 'r')
verbs = []
for l in f:
    verbs.append(l)

print(nouns[1] + verbs[1])

Upvotes: 1

Views: 1683

Answers (2)

cstoltze
cstoltze

Reputation: 916

Reading lines from a file includes the trailing newline. So each noun in the list looks like "noun\n". When printing the noun, because the noun includes a new line at the end, it causes the verb to be on the next line. What you want to do is remove the trailing newline.

To remove the trailing newline, use rstrip().

for l in f:
    nouns.append(l.rstrip())

See this answer for more detail about rstrip. https://stackoverflow.com/a/275025/6837080

Upvotes: 1

Kyle
Kyle

Reputation: 1066

You can use the zip method to iterate over multiple iterables.

Example

data1 = ["a", "b", "c"]
data2 = ["d", "e", "f"]
for a, b in zip(data1, data2):
    print("a: {0}, b: {1}".format(a, b))

returns

a: a, b: d a: b, b: e a: c, b: f

Upvotes: 1

Related Questions