Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python的打印格式中多次调用GUID函数_Python_Python 3.x - Fatal编程技术网

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

在python的打印格式中多次调用GUID函数,python,python-3.x,Python,Python 3.x,我有一个文本,我想看起来像这样 这是第一个guid:“fc52457d-42a5-4ad7-9619-c1513ce60a96”,这是第二个guid:“f6df6054-c433-48a6-bc22-449b037f4fc9” 我想用.format()实现这一点,但只引用uuid函数一次,并以某种方式调用它两次,如下所示: “这是第一个guid:{},这是第二个guid:{}”。格式(uuid.uuid4()*2) 我不想使用{0}和{1}表示法,如果我只使用例如{0}而不是空括号,我将为这两个

我有一个文本,我想看起来像这样

这是第一个guid:“fc52457d-42a5-4ad7-9619-c1513ce60a96”,这是第二个guid:“f6df6054-c433-48a6-bc22-449b037f4fc9”

我想用.format()实现这一点,但只引用uuid函数一次,并以某种方式调用它两次,如下所示:
“这是第一个guid:{},这是第二个guid:{}”。格式(uuid.uuid4()*2)

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

这是有效的:

'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[0], L[1])
30
这是生成器表达式:

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

除了如Mike Müller所示生成多个UUID并将其传递给format函数外,您还可以创造性地创建自己的“UUID字符串生成器”类型,该类型在调用
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
>>> list((uuid.uuid4() for  _ in range(2)))
[UUID('d45eaf67-5ba0-445f-adaa-318f989e2d60'),
 UUID('58fcaf7f-63af-4c7f-9f01-956db6923748')]
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