Python format函数的用法详解

原文转自:https://blog.csdn.net/it_python/article/details/81037078

1.通过位置来填充字符串
print('hello {0} i am {1}'.format('world','python'))    # 输入结果:hello world i am python
print('hello {} i am {}'.format('world','python') ) #输入结果:hello world i am python
print('hello {0} i am {1} . a now language-- {1}'.format('world','python')
# 输出结果:hello world i am python . a now language-- python
foramt会把参数按位置顺序来填充到字符串中,第一个参数是0,然后1 …… 
也可以不输入数字,这样也会按顺序来填充 
同一个参数可以填充多次,这个是format比%先进的地方

2.通过key来填充
obj = 'world'
name = 'python'
print('hello, {obj} ,i am {name}'.format(obj = obj,name = name))
# 输入结果:hello, world ,i am python
3.通过列表填充
list=['world','python']
print('hello {names[0]}  i am {names[1]}'.format(names=list))# 输出结果:hello world  i am python
print('hello {0[0]}  i am {0[1]}'.format(list)) #输出结果:hello world  i am python
4.通过字典填充
dict={‘obj’:’world’,’name’:’python’} 
print(‘hello {names[obj]} i am {names[name]}’.format(names=dict)) # hello world i am python 
注意访问字典的key,不用引号的

5.通过类的属性填充
class Names():
    obj='world'
    name='python'
 
print('hello {names.obj} i am {names.name}'.format(names=Names))#输入结果hello world i am python
6.使用魔法参数
args = [‘,’,’inx’] 
kwargs = {‘obj’: ‘world’, ‘name’: ‘python’} 
print(‘hello {obj} {} i am {name}’.format(*args, **kwargs))#输入结果:hello world , i am python

注意:魔法参数跟你函数中使用的性质是一样的:这里format(*args, **kwargs)) 等价于:format(‘,’,’inx’,obj = ‘world’,name = ‘python’)
--------------------- 
作者:honork 
来源:CSDN 
原文:https://blog.csdn.net/it_python/article/details/81037078 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/NeverLate_gogogo/article/details/85266356