简体   繁体   中英

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])

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: da: b, b: ea: c, b: f

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM