首页 > 解决方案 > 如果密码以数字开头,是否有更简单的方法可以再次生成密码?

问题描述

我正在尝试构建这个非常简单的“密码生成器”,我想知道如果密码以整数开头,是否有更简单的方法来生成新密码

choices = string.ascii_letters + string.digits

randomPass = random.sample(choices, length)

password = "".join(randomPass)
password1 = "".join(randomPass)

#checks password

if password[0].isdigit():
  print("password started with number generating another password...")

  if password1[0].isdigit():
    print("started with a number again, trying again...")

  else:
    print(password1)

else:
  print(password)

我这样做的方式根本没有效率,无论我这样做多少次,我仍然有可能在开头生成一个带有数字的密码,但我确信使用循环将消除数字是密码中的第一个字符,会让生活更轻松,我只是不知道怎么做,有人可以帮忙吗?

标签: python

解决方案


您的代码的直接修复是一个循环:

while password[0].isdigit():
    print("password started with number generating another password...")
    password = "".join(random.sample(choices, length))

但是,更好的是首先构造一个合法密码:仅从字母中获取第一个字符:

choices = string.ascii_letters + string.digits

first_letter = random.choice(string.ascii_letters)
randomPass = first_letter + ''.join(random.sample(choices, length-1))

推荐阅读