views:

39

answers:

4

Hello,

I am creating a random ID using the below code:

from random import *
import string

# The characters to make up the random password
chars = string.ascii_letters + string.digits

def random_password():

    return "".join(choice(chars) for x in range(32))

This will output something like:

60ff612332b741508bc4432e34ec1d3e

I would like the format to be in this format:

60ff6123-32b7-4150-8bc4-432e34ec1d3e

I was looking at the .split() method but can't see how to do this with a random id, also the hyphen's must be at these places so splitting them by a certain amount of digits is out. I'm asking is there a way to split these random id's by 8 number's then 4 etc.

Thanks

+3  A: 

What's wrong with generating every part separately? Like that:

def random_password():
    return "-".join(["".join(choice(chars) for x in range(n)) 
                     for n in (8, 4, 4, 4, 8)])
Łukasz
+1  A: 

how about simple concat?

>>> s="60ff612332b741508bc4432e34ec1d3e"
>>> s[:8]+"-"+s[8:12]+"-"+s[12:16]+"-"+s[16:20]+"-"+s[20:]
'60ff6123-32b7-4150-8bc4-432e34ec1d3e'
ghostdog74
+4  A: 

The uuid module can be used for generating UUIDs.

Ignacio Vazquez-Abrams
+1, but just a note for OP. only in >2.5
ghostdog74
It is available separately for earlier versions. http://zesty.ca/python/uuid.html
Ignacio Vazquez-Abrams
+1  A: 
pos = set([8, 12, 16])
print "".join(map(lambda x: (x[1], "%s-" % x[1])[x[0] in pos], list(enumerate(random_password()))))
ephes