0

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?

2 Answers 2

7

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])
Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.