将随机字符串连接到精确格式

时间:2010-03-31 10:21:45

标签: python string

我正在使用以下代码创建随机ID:

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

这将输出如下内容:

60ff612332b741508bc4432e34ec1d3e

我希望格式为这种格式:

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

我正在查看.split()方法,但无法看到如何使用随机ID执行此操作,连字符也必须位于这些位置,因此将它们拆分一定数量的数字。我问有没有办法将这些随机id分成8个数字然后4个等等。

由于

4 个答案:

答案 0 :(得分:4)

uuid模块可用于生成UUID。

答案 1 :(得分:3)

分别生成每个部件有什么问题?像那样:

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

答案 2 :(得分:2)

简单的concat怎么样?

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

答案 3 :(得分:1)

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