Wednesday, February 28, 2024

Random module and String module

Example 1: 


import random,string


list_of_alphabets = [letter
for letter in string.ascii_letters]
random.shuffle(list_of_alphabets)
print(list_of_alphabets)
Output:
['Y', 'M', 'b', 'F', 'X', 'r', 'm', 'J', 'w', 'o', 
'Z', 'U', 'g', 'l', 'c', 'f', 'A', 'B', 'N', 'G', 'L', 'V', 'h', 
'n', 'I', 'T', 'x', 'y', 'E', 'H', 'D', 'q', 'd', 'O', 't', 'R', 
'S', 's', 'v', 'P', 'e', 'Q', 'k', 'p', 'i', 'W', 'K', 'C', 'j', 'z',
 'a', 'u']

Example 2:

import random
import string


def generate_random_password(length=12):
if length < 8 or length > 16:
raise ValueError("Password length must be between 8 and 16 characters")

password = []

# Combine letters and symbols
list_of_chars = [letter for letter in string.ascii_letters]
list_of_symbols = [symbol
for symbol in string.punctuation]
list_of_chars.extend(list_of_symbols)

# Shuffle the characters
random.shuffle(list_of_chars)

# Select characters for the password
for _ in range(length):
password.append(
random.choice(list_of_chars))

return ''.join(password)


# Generate a random password of length between 8 and 16
random_password = generate_random_password(random.randint(8, 16))
print(random_password)

Output:
x#=K@_&p.D

No comments:

Post a Comment