import string
import random
def generator():
password = ""
passwordlength = random.randint(8,12)
length = 0
while length < passwordlength:
password = password + random.choice(string.digits + string.ascii_letters + "!","$","%","^","&","*","(",")","-","_","=","+")
length = len(password)
print(password)
generator()
我在这里有这个代码,但是当我运行它时,它会立即出现错误“choice()需要2个位置参数但是给出了13个”。我对于什么是错误一无所知
答案 0 :(得分:1)
你应该使用&#39; +&#39;代替&#39;而不是&#39;你的代码
就是这样:
random.choice(string.digits + string.ascii_letters + "!"+"$"+"%"+"^"+"&"+"*"+"("+")"+"-"+"_"+"="+"+")
更好的版本可能就是这个
random.choice(string.digits + string.ascii_letters + "!$%^&*()-_=+")
答案 1 :(得分:1)
您必须传递list
或string
:
import string
import random
def generator():
password = ""
passwordlength = random.randint(8,12)
length = 0
signal_list = ["!","$","%","^","&","*","(",")","-","_","=","+"]
my_list = []
my_list.extend(string.digits)
my_list.extend(string.ascii_letters)
my_list.extend(signal_list)
while length < passwordlength:
password = password + random.choice(my_list)
length = len(password)
print(password)
generator()
答案 2 :(得分:0)
当你致电random.choice
时,你应该只传递一个类似序列的对象,你需要一个随机项目。但是你的函数调用
random.choice(string.digits + string.ascii_letters + "!","$","%","^","&","*","(",")","-","_","=","+")
传递一串数字和字母,然后将一大堆标点字符作为单独的字符串传递,所以不是给random.choice
一个类似序列的对象,而是给它一大堆它们。
[技术说明。 random
模块提供的大多数函数实际上是对random.Random
类的隐藏实例的方法调用,因此它们会自动作为第一个参数传递self
。您的错误消息表明&#34; choice()需要2个位置参数&#34;,但它所期望的第一个位置参数是该隐藏self
实例的random.Random
。这有点令人困惑,因为表面看起来random.choice
只需要一个参数,当它真的取2时,但第一个会自动传递。
FWIW,这是编写函数的更紧凑的方法:
import string
from random import choice, randint
def generator():
pool = string.digits + string.ascii_letters + '!$%^&*()-_=+'
return ''.join([choice(pool) for _ in range(randint(8, 12))])
# Test
for i in range(10):
s = generator()
print(i, s, len(s))
典型输出
0 b%SiMq)e 8
1 gX2ha5b39 9
2 iibe!qvK4s4B 12
3 a!nLrvNuHUz 11
4 -B5G0+LBFQ 10
5 %11*qS1!8 9
6 rX6cq^+=zL= 11
7 R)mNi3Q=xK 10
8 HKDNQH-Tw 9
9 d&h9HITP 8