2009
Snippet to generate a random word in python

Since I haven’t posted here in a while, I figured I’d whip up this example real quick. It illustrates the usage of the random function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #!/usr/bin/python import random from time import time def generateWord(): char_array = 'abcdefghijklmnopqrstuvwxyz' random.seed(time()) word = '' for i in range(0, 8): # 8 letter word word += char_array[random.randint(0, 25)] return word if __name__ == '__main__': print generateWord() |
2 Responses (rss) (trackback)
Evens
May I submit another solution ?
#!/usr/bin/python
import random
import string
def generateWord():
char_array = string.ascii_lowercase
word = "".join(random.choice(char_array) for i in range(8))
return word
if __name__ == "__main__":
print generateWord()
Concerning the random.seed() function :
- You don’t need to random.seed() unless you need a specific seeding value.
- You don’t need to use time.time() because by default random.seed() will use the current time to seed the generator.
- You dont need to random.seed() since the generator will be seeded when the random module is imported.



DreamCatcher
man! its been long i have been in touch of coding..ur blog has changed so much!