在python的打印格式中多次调用GUID函数

2024-04-19 08:55:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本,我想看起来像这样。你知道吗

This is a first guid: "fc52457d-42a5-4ad7-9619-c1513ce60a96" and this is a second one: "f6df6054-c433-48a6-bc22-449b037f4fc9"

我希望通过.format()实现这一点,但只引用一次uuid函数,然后以某种方式调用它两次,类似于: "This is a first guid: {} and this is a second one: {}".format(uuid.uuid4()*2)

我不想使用{0}和{1}表示法,如果我只使用例如{0}而不是空括号,我将为这两个实例获得相同的GUID。 有没有一种方法可以用.format多次调用uuid函数?你知道吗


Tags: and函数文本formatuuidisthisone
2条回答

这样做有效:

'This is a first guid: {} and this is a second one: {}'.format(*(uuid.uuid4()
                                                               for _ in range(2)))

印刷品:

'This is a first guid: c5842b59-795d-452f-b0cd-ba5c7369dde7 and this is a second one: 8c20f372-8044-4b82-bbbd-0e667fb14ed3'

可以使用*将指定数量的参数传递给函数。例如:

def add(a, b):
    return a + b

>>> L = [10, 20

这是:

>>> add(*L)
>>> 30

相当于:

>>> add(L[0], L[1])
30

这是生成器表达式:

>>>(uuid.uuid4for for _ in range(2))
<generator object <genexpr> at 0x10e4d1620>

将其转换为列表以查看生成的内容:

>>> list((uuid.uuid4() for  _ in range(2)))
[UUID('d45eaf67-5ba0-445f-adaa-318f989e2d60'),
 UUID('58fcaf7f-63af-4c7f-9f01-956db6923748')]

除了像Mike Müller所展示的那样生成多个UUID并将其传递给format函数之外,您还可以创造性地创建自己的“UUID string generator”类型,在调用str()时创建一个新的UUID:

class UuidStringGenerator:
    def __str__ (self):
        return str(uuid.uuid4())

print('First: {uuid}\nSecond: {uuid}'.format(uuid=UuidStringGenerator()))
# First: dd38d750-301b-4dec-bf18-4554a96942d8
# Second: bcb27d9f-378d-401e-9746-043834bece09

相关问题 更多 >