Python 生成指定位数随机不重复密码,必须包含大小字母数字特殊字符

#生成指定位数随机不重复密码,必须包含大小字母数字特殊字符
import random
import string
def random_password(num):
result=’’
choice=‘0123456789’+string.ascii_lowercase+string.ascii_uppercase+string.punctuation
result += random.choice(‘0123456789’)
result += random.choice(string.ascii_lowercase)
result += random.choice(string.ascii_uppercase)
result += random.choice(string.punctuation)
for i in range(num-4):
a = random.choice(choice)
if a not in result:
result+=a
return result

random_password(10)

#方法2
def random_password():
import random
import string
string_lower = string.ascii_lowercase
string_upper = string.ascii_uppercase
string_digits = string.digits
string_all = string_lower+string_upper+string_digits
string.password = ‘’
for i in range(10):
if i == 0:
string.password+=random.choice(string_lower)
elif i == 1:
string.password+=random.choice(string_upper)
elif i == 2:
string.password+=random.choice(string_digits)
else:
string.password+=random.choice(string_all)
return string.password

print(random_password())

你可能感兴趣的:(个人python小程序)