user3803187
user3803187

Reputation: 11

Does anyone know why this python code is just returning a single letter rather than a full word?

import random
import requests 

response = requests.get("http://www.mit.edu/~ecprice/wordlist.10000")
txt = response.text 
    
firstWord = random.choice(txt)

print(firstWord)

I'd like this to return one of the words in that mit word list, but it seems to just be outputting singular letters and I'm really not sure why. Any guidance would be super appreciated thanks everyone

Upvotes: 1

Views: 371

Answers (1)

Ecko
Ecko

Reputation: 1090

random.choice() returns individual characters when given a string input. If you want it to give you full words, you can run random.choice(txt.split()) instead. This will turn the string txt into a tuple of individual words by splitting at every whitespace character, then choose a random element from the tuple (which will be a word).

Upvotes: 4

Related Questions