动态参数

动态参数

1.

def show(*arg):
    print(arg,type(arg))
show(1,22,33,44)
(1, 22, 33, 44) <class 'tuple'>   转化为元组

2.

def show(**arg):
    print(arg,type(arg))
show(n1=1,n2=22,n3=33,n4=44)
{'n1': 1, 'n2': 22, 'n3': 33, 'n4': 44} <class 'dict'>   转化为字典

3.

def show(*args,**kargs):
    print(args,type(args))
    print(kargs, type(kargs))
show(1,22,33,44,n1=55,k2=66)
(1, 22, 33, 44) <class 'tuple'>   转化为元组
{'n1': 55, 'k2': 66} <class 'dict'>  转化为字典

4.

def show(*args,**kargs):
    print(args,type(args))
    print(kargs, type(kargs))
l = [1,22,33,44]
d=  {'n1':55,'k2':66}
show(*l,**d)
(1, 22, 33, 44) <class 'tuple'>   转化为元组
{'n1': 55, 'k2': 66} <class 'dict'>  转化为字典

使用动态参数实现字符串的格式化

1.

s = "{0} is {1}"
result = s.format('dan','beautiful')
print(result)
dan is beautiful

2.

l = ['dan','beautiful']
result = s.format(*l)
print(result)
dan is beautiful

3.

s = "{name} is {acter}"
result = s.format(name='dan',acter='nice')
print(result)
dan is nice

4.

d = {'name':'dan','acter':'nice'}
result = s.format(**d)
print(result)
dan is nice

你可能感兴趣的:(Python)