python3.0将范围循环输出分配给variab

2024-10-04 03:17:39 发布

您现在位置:Python中文网/ 问答频道 /正文

#Imports
import string
import random
import time


digits = string.digits
letters = string.ascii_letters
punctuation =("!\"\<>@#£$%^&*")
PasswordCode = letters+punctuation+digits

PassLenInput = input("How long should the password be?")
PassLenInput = int(PassLenInput)
for i in range(PassLenInput):
    print(random.choice(PasswordCode),end="")

我的输出如下

How long should the password be?4
GtRA

我想将这个输出保存到一个名为pass的变量中,然后将该变量保存到一个文本文件中

谢谢


Tags: theimportstringrandompasswordbeimportslong
2条回答

看看这个答案

#Imports
import string
import random
import time


digits = string.digits
letters = string.ascii_letters
punctuation =("!\"\<>@#£$%^&*")
PasswordCode = letters+punctuation+digits

PassLenInput = input("How long should the password be?")
PassLenInput = int(PassLenInput)
password = ""
for i in range(PassLenInput):
    password += random.choice(PasswordCode)
    print(password)

#Save Password
with open("password.txt", "w") as save_password:
    save_password.write(password)

我优化了导入并将密码写入了一个文件:

from string import digits
from string import ascii_letters as letters
import random

punctuation =("!\"\<>@#£$%^&*")
PasswordCode = letters+punctuation+digits

PassLenInput = int(input("How long should the password be?"))

password = ''

for i in range(PassLenInput):
    password += random.choice(PasswordCode)

with open('password_file.txt', 'w') as f:
    f.write(password)

相关问题 更多 >