开发者

Hyphenate a random string to an exact format

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_pa开发者_开发百科ssword():

    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


The uuid module can be used for generating UUIDs.


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)])


how about simple concat?

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


pos = set([8, 12, 16])
print "".join(map(lambda x: (x[1], "%s-" % x[1])[x[0] in pos], list(enumerate(random_password()))))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜