Python Functions for Generating Random Captcha and Password Strings
This article presents three Python approaches for generating random strings, including single captcha-like codes, password lists, and batch generation functions, demonstrating the use of the random and string modules to create alphanumeric sequences.
The following examples show how to use Python's random and string modules to create random alphanumeric strings that can serve as captchas, passwords, or bulk test data.
Single captcha-like code (method 1):
import random, string
def one_test():
s = ""
for i in range(0, 17):
if random.randint(0, 1) == 0:
# generate a letter
s = s + chr(random.randint(65, 90))
else:
# generate a digit
s = s + str(random.randint(0, 9))
return sSingle password list (method 2):
import random, string
passwd = []
for i in range(20):
if random.randint(0, 1):
letter = random.choice(string.ascii_uppercase)
passwd.append(letter)
else:
letter = random.choice(string.digits)
passwd.append(letter)
print("".join(passwd))Batch generation of multiple codes (method 3):
import random, string
def one_test():
s = ""
for i in range(0, 17):
if random.randint(0, 1) == 0:
# generate a letter
s = s + chr(random.randint(65, 90))
else:
# generate a digit
s = s + str(random.randint(0, 9))
return s
def more_test(xxx): # generate a custom number of codes
aaa = []
for i in range(0, xxx):
aaa.append(one_test())
print(aaa)
if __name__ == '__main__':
more_test(10)These snippets illustrate basic techniques for random string generation, useful for testing, security exercises, or creating simple verification codes.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.