python==format, *args, **kwargs

版权声明:转载请注明出处。 https://blog.csdn.net/Xin_101/article/details/83784322

1 *args, **kwargs

  • *args和**kwargs是python中的可变参数;
  • *args表示任何多个无名参数,是tuple类型;
  • **表示关键字参数,是dict类型;
  • 同时使用*args和kwargs时,*args必须放在kwargs前面;
# 源码
def foo(*args, **kwargs):
	print("args={}".format(args))
	print("kwargs={}".format(kwargs))
	for i in range(10):
		print("**",end='')
if __name__ == "__main__":
	# tuple类型数据
	foo(1, 2, 3, 4)
	# dict类型数据
	foo(a=1, b=2, c=3)
	# tuple+dict类型数据
	foo(1, 2, 3, 4, a=1, b=2, c=3)
# 结果
# *args为tuple类型
# **kwargs为dict类型
args=(1, 2, 3)
kwargs={}
********************
args=()
kwargs={'a': 1, 'b': 2, 'c': 3}
********************
args=(1, 2, 3)
kwargs={'a': 1, 'b': 2, 'c': 3}
********************

注意

# *args, **kwargs先后顺序错误
def foo(**kwargs, *args):
# 结果
 File "<ipython-input-54-434a959009b6>", line 1
    def foo(**kwargs, *args):
                      ^
SyntaxError: invalid syntax

2 format

  • format是Python2.6开始新增的格式化字符串函数,形式str.format();
  • 使用形式"{}{}".format("a","b");
  • 传统%引用变量输出,即print("%d" %a);
  • format参数个数不受限制.

2.1 默认输出

# 源码
a = "{} {}".format("xin", "daqi")
b = "{},{}".format("OK","See you later!")
print(type(a))
print(a)
print(type(b))
print(b)
# 结果
# format输出格式为字符串,默认按照参数先后位置输出
<class 'str'>
xin daqi
<class 'str'>
OK,See you later!

2.2 指定参数顺序输出

# 源码
a = 'OK'
b = "Let's go!"
o1 = "{}{}".format(b,a)
o2 = "{1},{0}".format(b,a)
print(o1)
print(o2)
# 结果
# 按照指定顺序输出,在{}中指定变量
# format参数从0开始标注
Let's go!OK
OK,Let's go!

2.3 指定输出变量

# 源码
userInfo = {"name":"xin daqi", "sex":"male"}
print("姓名:{name}, 性别:{sex}".format(**userInfo))
# 结果
# 指定输出变量
# format参数使用dict类型
# **kwargs参数
姓名:xin daqi,性别:male

2.4 传入对象参数

# 源码
class Test(object):
	def __init__(self, value):
		self.value = value
useTest = Test(2)
print("{0.value}".format(useTest))
# 结果
# 传入对象
# 输出变量
2

[参考文献]
[1]https://www.cnblogs.com/goodhacker/p/3360721.html
[2]http://www.runoob.com/python/att-string-format.html


猜你喜欢

转载自blog.csdn.net/Xin_101/article/details/83784322
今日推荐