简体   繁体   中英

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

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$

What I'm really wanting to do is something that just randomly organizes the 94characters in the chars var. 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

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.

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 :

>>> 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 ; the point is that the same element of chars is never drawn twice. random.sample("aa", 2) will give ["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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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