I am using Python 3 and I am very new to this.
import random
words = random.sample(open('letters.txt').readlines(), 9)
print(words)
I have found solutions but they never seem to work in Python 3.
I am using Python 3 and I am very new to this.
import random
words = random.sample(open('letters.txt').readlines(), 9)
print(words)
I have found solutions but they never seem to work in Python 3.
Use rstrip()
to remove the \n
newline character:
import random
words = [x.rstrip() for x in random.sample(open('in.txt').readlines(), 9)]
grid = [words[i:i + 3] for i in range(0, len(words), 3)]
[['BLUE', 'ANGRY', 'RED'], ['HAPPY', 'FOO', 'ORANGE'], ['JOYFUL', 'YELLOW', 'SAD']]
If you want to print them out:
import random
with open('in.txt') as f: # with closes your files automatically
words = random.sample([x.rstrip() for x in f],9)
grid = [words[i:i + 3] for i in range(0, len(words), 3)]
for x,y,z in grid:
print (x,y,z)
In [5]: with open('in.txt') as f: # with closes your files automatically
...: words = random.sample([x.rstrip() for x in f],9)
...: grid = [words[i:i + 3] for i in range(0, len(words), 3)]
...: for x,y,z in grid:
...: print (x,y,z)
...:
BLUE GREEN SAD
RED JOYFUL FOO
ORANGE HAPPY YELLOW
After making a little search in stackoverflow I found this Print new output on same line
So perhaps could do something like (this code is not tested):
import random
// We store all the words to keep reference to the one is not displayed
dictionary = open('words.txt').readlines()
words = random.sample(dictionary, 9)
for index in range(9)
ending = ' '
if index+1 % 3 == 0
ending = '\n'
print(words[i], end=ending)