简体   繁体   中英

Python readlines() splits line into two

I'm reading lines from a text file. In the text file there is a single word in each line. I can read and print the word from the file, but not the whole word is printed out on one line. The word is split into two. The letters of the printed word are mixed.

Here is my code:

import random
fruitlist = open('fruits.txt', 'r')

reading_line = fruitlist.readlines()
word = random.choice(reading_line)
mixed_word = ''.join(random.sample(word,len(word)))

print(mixed_word)

fruitlist.close()

How can I display one word on a line?

EDIT:

this is the content of the text file:

pinapple    
pear    
strawberry    
cherry    
papaya  

The script should print one of these words (with their letters mixed) like this:

erpa

(This would be the equivalent of pear)

Right now it is displayed like this:

erp  
a

that's because you're also shuffling the line termination chars that readlines or line iterators include in the line. Use strip() to get rid of them (or rstrip() )

Do it like this (avoid readlines BTW):

with open('fruits.txt', 'r') as fruitlist:
    reading_line = [x.strip() for x in fruitlist]
    word = random.choice(reading_line)
    mixed_word = ''.join(random.sample(word,len(word)))

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