import random
import string
newPassword = input("Do you want a new password?: ")
characters = input("How many characters do you want your new password to have?: ")
def passwordGenerator():
if newPassword.lower() == "yes":
print("Your new password is:")
for i in range(int(characters)):
print(''.join(random.choices(string.ascii_uppercase + string.digits)))
elif newPassword.lower() == "no":
print("Okay, maybe some other time!")
else:
print("Invalid input!")
passwordGenerator()
运行代码时,随机字符在单独的行中打印出来,例如:
Y
B
3
R
M
如何将这些字符连接在同一行上以显示为字符串?
答案 0 :(得分:0)
只需尝试一下:
import random
import string
newPassword = input("Do you want a new password?: ")
characters = input("How many characters do you want your new password to have?: ")
def passwordGenerator():
if newPassword.lower() == "yes":
password = ''
for i in range(int(characters)):
password += ''.join(random.choices(string.ascii_uppercase + string.digits))
print("Your new password is : " + password)
elif newPassword.lower() == "no":
print("Okay, maybe some other time!")
else:
print("Invalid input!")
passwordGenerator()
您正在向空词添加字母,因此在for..in
循环之后,您将获得随机密码。
答案 1 :(得分:0)
简化功能。
newPassword = input("Do you want a new password?: ")
newPassword = newPassword.lower()
characters = input("How many characters do you want your new password to have?: ")
chars = string.ascii_uppercase + string.digits
def passwordGenerator(length):
return ''.join(random.choice(chars) for x in range(length))
if newPassword == 'yes':
print(passwordGenerator(characters))
elif newPassword == 'no':
print("Okay, maybe some other time!")
else:
print("Invalid input!")