PapT PapT - 1 month ago 20
Python Question

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

Answer

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