首页 > 解决方案 > I have a problem the random.choice() function as it prints one LETTER in a list of WORDS

问题描述

I am new to python and programming in general and I was trying to make a hangman game. I downloaded a dictionary text file and opened it in pycharm and I applied the random.choice() function on it and it only printed a letter of a random word in the .txt file:

import random

f = open ("/home/ar/Downloads/sowpods.txt")

sowpods = f.read()

sowpods = random.choice(sowpods)

print(sowpods)

标签: python

解决方案


You first need to convert from a list of characters to a list of words. You can do this using string.split().

import random

f = open ("/home/ar/Downloads/sowpods.txt")

sowpods = f.read().split()

sowpods = random.choice(sowpods)

print(sowpods)

推荐阅读