简体   繁体   English

在Python中创建随机字符串而不重复字符

[英]Creating a random string in Python without duplicating characters

So what I am doing is creating a 94char key that uses string.digits + string.ascii_letters + string.punctuation 所以我正在做的是创建一个使用string.digits + string.ascii_letters + string.punctuation的94char键

I use this for generating the key (grabbed from this site thanks :) ) 我用它来生成密钥(从这个网站抢夺了:))

def key_pass(size=94, chars=string.digits + string.ascii_letters + string.punctuation):
    return ''.join(random.choice(chars) for x in range(size))

which creates something like this 9bMMqy-lB6Mt},bOxr@1ljey_\\Z\\gk`xRJBP;3YFR*i<N<!MB}_|0p3f5Q"l8'xEj)WHYGk7O]vQZ1cZ'(diMKS*gW%u$ 它会创建类似以下内容的9bMMqy-lB6Mt},bOxr@1ljey_\\Z\\gk`xRJBP;3YFR*i<N<!MB}_|0p3f5Q"l8'xEj)WHYGk7O]vQZ1cZ'(diMKS*gW%u$

What I'm really wanting to do is something that just randomly organizes the 94characters in the chars var. 我真正想做的是随机地将chars var中的94个chars组织起来。 So I can't have anything that repeats I just cant seem to get the right way to implement an if statement that would check the variable 因此,我无法重复任何事情,只是似乎无法找到正确的方法来实现将检查变量的if语句

Any advice? 有什么建议吗?

Put them in a list, then use random shuffle to err, well, shuffle them about, and then join them back to make a string. 将它们放在列表中,然后使用random混洗来犯错,好吧,将它们混洗,然后再将它们重新组合成一个字符串。

import string
import random

all_chars = list(string.digits + string.ascii_letters + string.punctuation)
random.shuffle(all_chars)
print ''.join(all_chars[:94])

I'd use random.sample : 我会用random.sample

>>> import string, random
>>> chars=string.digits + string.ascii_letters + string.punctuation
>>> ''.join(random.sample(chars, 4))
'e_/p'
>>> ''.join(random.sample(chars, 10))
'a4NSq`%tQ#'

You're guaranteed never to have duplicates-- assuming the original is unique, that is, which could be ensured by a call to set ; 保证您永远不会重复-假设原件是唯一的,也就是说,可以通过调用set来确保; the point is that the same element of chars is never drawn twice. 关键是chars的相同元素永远不会绘制两次。 random.sample("aa", 2) will give ["a", "a"] . random.sample("aa", 2)将给出["a", "a"] If you ask for more elements than you have, you'll get a nice error: 如果您请求的元素超出了您的要求,则会收到一个不错的错误消息:

>>> ''.join(random.sample(chars, 100))
Traceback (most recent call last):
  File "<ipython-input-9-80959adcfe83>", line 1, in <module>
    ''.join(random.sample(chars, 100))
  File "/usr/lib/python2.7/random.py", line 320, in sample
    raise ValueError("sample larger than population")
ValueError: sample larger than population

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM