如何将密码显示为星号?Python密码检查器代码优化需求
解决密码星号输出的两种方案
方案1:仅修改输出为星号(输入仍明文显示)
直接把输出语句里的明文密码替换成对应长度的星号即可,利用字符串乘法生成和密码长度一致的*串:
username = input("What is your name?") password = input("What is your password?") password_length = len(password) # 替换原输出中的明文密码为星号 print(f'{username}, your password, {"*" * password_length}, is {password_length} letters long')
方案2:输入时隐藏密码(更安全)
如果想要输入密码时就不显示明文,推荐使用Python内置的getpass模块,它会在输入密码时隐藏输入内容,同时输出时依然用星号展示长度:
import getpass username = input("What is your name?") # 使用getpass输入密码,输入时不会显示明文 password = getpass.getpass("What is your password?") password_length = len(password) print(f'{username}, your password, {"*" * password_length}, is {password_length} letters long')
这样修改后,输出阶段不会暴露明文密码;方案2还能进一步避免输入时的密码泄露,更符合密码检查器的安全需求。
内容的提问来源于stack exchange,提问作者snowhow
相关产品推荐
相关产品推荐

