NotAName
NotAName

Reputation: 4322

Output of shuffling a string is printed on 2 lines of output

I've decide to practice solving anagrams, something I'm very bad at. I got 1000 most common words of English language, filtered those under 5 letters and over 9 and then wrote a simple script:

import random
from random import randint

words = []
file = 'new_words.txt'

with open(file) as f:
    for line in f:
        words.append(line)

while True:
    i = randint(0, (len(words)-1))

    question_list = list(words[i])
    random.shuffle(question_list)

    print(f"{''.join(question_list)}")
    print(f'Please solve the anagram. Type "exit" to quit of "next" to pass:\n')
    answer = input()

    if answer == 'exit':
        break
    elif answer == 'pass':
        pass
    elif answer == words[i]:
        print('Correct!')
    elif answer != words[i]:
        print('Epic fail...\n\n')

Now for some reason the output of the line print(f"{''.join(question_list)}") is printed over 2 lines like so:

o
nzcieger

Which is an anagram for 'recognize'. It also prints random numbers on letters per line:

ly
erla 

Sometimes the whole anagram is printed properly.

I can't figure out what's causing this.

EDIT: Link to my filtered file with words

Upvotes: 0

Views: 136

Answers (2)

Kousik
Kousik

Reputation: 475

You can add this below question_list = list(words[i]): to remove the new line character read from the file for each of the line.

question_list.remove('\n')

Since the new line character occur only one time in the list we don't need to iterate over the list. It will just remove the first occurrence of '\n' from the list.

Or

del question_list[-1]

cause we know the exact index location of \n

Upvotes: 0

RealPawPaw
RealPawPaw

Reputation: 986

You have to strip the newlines out of the word.

Basically, your text file is actually formatted as a word on each line and a '\n' character at the end of each line. When you call random.shuffle(question_list), your are shuffling the characters of the word along with the newline character, so the newline is also shuffled! When you print out the 'shuffled' word, Python prints the word out with the newline, so you get the word randomly split between two lines.

In order to solve this issue, you can probably use the str.strip() function (but that would require you cast the list to a string) or just add this to below question_list = list(words[i]):

for character in question_list:
    if character == '\n':
        question_list.remove(character)

Upvotes: 1

Related Questions