0
例如:什麼是最簡潔的方式將變量傳遞給python string.format?
def print_template(a,b):
c="the c"
template="{a} {b} {c}"
print template.format(a=a,b=b,c=c)
這是工作,但格式函數的參數列表是一個有點冗長。無論如何要讓它更簡潔?也許通過傳遞所有的局部變量到格式函數?
例如:什麼是最簡潔的方式將變量傳遞給python string.format?
def print_template(a,b):
c="the c"
template="{a} {b} {c}"
print template.format(a=a,b=b,c=c)
這是工作,但格式函數的參數列表是一個有點冗長。無論如何要讓它更簡潔?也許通過傳遞所有的局部變量到格式函數?
您可以通過局部變量,如果你想:
def print_template(a,b):
c="the c"
template="{a} {b} {c}"
print template.format(**vars())
演示:
>>> print_template(1,2)
1 2 the c
謝謝,alko,它的效果很好 – yigal
局部變量可以包括其他對象,功能和內容。你確定要打印所有當地人? – aIKid