顯示具有 argument 標籤的文章。 顯示所有文章
顯示具有 argument 標籤的文章。 顯示所有文章

2012/06/11

Python: 頑固的 variable length argument

這邊卡了很久,做個筆記...

可變長度的參數傳遞
def p(fmt, *arg):
    print fmt % arg

# 傳多個參數
s1 = "hello"
s2 = "world"
p("%s %s", s1, s2)

# 把 list 的 element 當作參數
l = ["Allen", "Billy", "Elmer"]
p("%s %s %s", *tuple(l))

# 混合模式
l = ["Allen", "Billy", "Elmer"]
s = "hello"
p("%s, %s %s %s", *((s, ) + tuple(l)))
Output:
hello world
Allen Billy Elmer
hello, Allen Billy Elmer