天天看點

[python]動态參數

動态參數

show(*arg)代表參數是一個元組(貌似清單也行),show(11,22,33)

show(**arg)代表參數是一個字典 show(n1=11,n2=22,n3=33)

也可結合show(*arg,**dic) show(11,22,n1=11,n2=22)

傳變量名:

a=(1,2,3)##元組,清單

show(*a)

b={‘x':8,'y':9}##字典

show(**b)

使用動态參數格式化字元串:

format函數

>>> s1="{0} is {1}"##元組,清單方法

>>> s1.format('cxj','talent')##會把字元串‘cxj’代入{0},以此類推

'cxj is talent'

>>> l1=['cxj','talent']

>>> s1.format(*l1)##傳入清單變量

'cxj is talent'

>>>

>>> s2 = "{name} is {what}"##字典方法

>>> s2.format(name='cxj',what='tc')##會把字元串‘cxj’代入{name},以此類推

'cxj is tc'

>>> k2={'name':'cxj','what':'student'}##注意這裡字典的key是name和what,和s2中定義的字元相同

>>> s2.format(**k2)##傳入字典變量

'cxj is student'