Python code to generate random string

Today I wrote a small piece of Python code to generate random string. The string will have only the characters: 0-9, A-Z, a-z.

word = ''
for i in range(wordLen):
word += random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')


Here is the complete source code that generates a large file that has a random word one per line.

import random

def get_random_word(wordLen):
word = ''
for i in range(wordLen):
word += random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')
return word

def main():
fout = open('word_list.txt', 'w')
for i in range(100000000):
wordLen = random.randint(5, 15)
word = ran_word(wordLen)
if i % 500000 == 0:
fout.close()
fout = open('word_list.txt', 'a')
print i
fout.write(word+"\n")
fout.close()

main()

Comments

Will said…
Here's a little project I did recently to build a cryptogram generator. This function builds a dictionary with each letter associated with a random letter, and spaces and punctuation associated with themselves. I'm very new to Python and programming.



def abcRandom():
#establish ABCs
ogABC = []
for i in range(len(string.lowercase)):
ogABC.append(string.lowercase[i])
#establish randomized ABCs
shuffleABC = []
for i in range(len(string.lowercase)):
shuffleABC.append(string.lowercase[i])
random.shuffle(shuffleABC)
#build dictionary of ordered/randomized ABCs.
dictABC = {' ': ' '}
for i in map(None, ogABC, shuffleABC):
dictABC[i[0]] = i[-1]
#add punctuation to dictionary. Punctuation will remain the same.
for i in range(len(string.punctuation)):
dictABC[string.punctuation[i]] = string.punctuation[i]

return dictABC


Boy, blogger needs a code tag.
Tamim Shahriar said…
Thanks for sharing the code. And yes, there should be a tag for code.
Vlad Starostin said…
This comment has been removed by the author.
Vlad Starostin said…
There is no need to use "for" cycle in get_random_word function.

def get_random_word(word_len):
return ('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') * word_len
Henry Nugraha said…
Q,
That way you will not get a random string, you will only get a repeated string.
Jim said…
an easy way for random strings is to import random and use chr():

import random
s=''
for i in range(1, 4): s += chr(random.randint(97, 122))

print s
many said…
why not simply do:

word = ''.join([random.choice('abcdefghijklmnoprstuvwyxzABCDEFGHIJKLMNOPRSTUVWXYZ') for i in range(100)])
Jagan said…
Thanks a lot. I am using the first code snippet to generate Email Activation Key for new users in my site.
Mark Zeta said…
This looks better, but same concept

word = ''
for i in range(wordLen):
word += random.choice(string.ascii_letters)

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code