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
版權宣告:本文為博主原創文章,轉載請附上博文連結!