python - 如果密码以数字开头,是否有更简单的方法可以再次生成密码?
问题描述
我正在尝试构建这个非常简单的“密码生成器”,我想知道如果密码以整数开头,是否有更简单的方法来生成新密码
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)
我这样做的方式根本没有效率,无论我这样做多少次,我仍然有可能在开头生成一个带有数字的密码,但我确信使用循环将消除数字是密码中的第一个字符,会让生活更轻松,我只是不知道怎么做,有人可以帮忙吗?
解决方案
您的代码的直接修复是一个循环:
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))
推荐阅读
- python - find() 方法找不到我能找到的
- python - psycopg2 copy_to 在插入期间将浮点值解释为字符串
- java - 线程睡眠冻结了我的代码。Java 客户端-服务器通信
- xamarin.forms - Xamarin 在单元格值之间形成笔划线?
- java - IntellijIDEA 2021.2.2 无法识别从 jar 文件导入到 gradle 模块的类
- ffmpeg - 为什么 FFmpeg 从一组图像创建后视频尺寸会发生变化?
- java - 具有动态方法参数类型的 Jackson TypeReference
- c++ - 使用堆栈的内存错误代码 0xC0000005
- haskell - 无法将类型“Integer”与“Int”匹配
- flutter - Flutter中如何避免在ListView、GridView构建器中使用图片的OOM?