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 ……
也可以不输入数字,这样也会按顺序来填充
但是不允许一个填充数字,一个不填充
2.通过key来填充
obj1 = ‘world’
name1 = ‘python’
print(‘hello, {obj} ,i am {name}’.format(obj = obj1,name = name1))
输入结果: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