字符串是Python程序重要的數(shù)據(jù)類型,到目前為止,我們輸出的字符串的內(nèi)容都是固定的,但有時(shí)候通過字符串輸出的內(nèi)容不是固定的,這個(gè)時(shí)候需要使用format來處理字符串,輸出不固定的內(nèi)容。
字符串format由兩個(gè)部分組成,字符串模板和模板數(shù)據(jù)內(nèi)容組成,通過大括號(hào){}
,就可以把模板數(shù)據(jù)內(nèi)容嵌到字符串模板對(duì)應(yīng)的位置。
# 字符串模板
template = 'Hello {}'
# 模板數(shù)據(jù)內(nèi)容
world = 'World'
result = template.format(world)
print(result) # ==> Hello World
如果模板中{}
比較多,則容易錯(cuò)亂,那么在format的時(shí)候也可以指定模板數(shù)據(jù)內(nèi)容的順序。
# 指定順序
template = 'Hello {0}, Hello {1}, Hello {2}, Hello {3}.'
result = template.format('World', 'China', 'Beijing', 'imooc')
print(result) # ==> Hello World, Hello China, Hello Beijing, Hello imooc.
# 調(diào)整順序
template = 'Hello {3}, Hello {2}, Hello {1}, Hello {0}.'
result = template.format('World', 'China', 'Beijing', 'imooc')
print(result) # ==> Hello imooc, Hello Beijing, Hello China, Hello World.
除了使用順序,還可以指定對(duì)應(yīng)的名字,使得在format過程更加清晰。
# 指定{}的名字w,c,b,i
template = 'Hello {w}, Hello {c}, Hello , Hello {i}.'
world = 'World'
china = 'China'
beijing = 'Beijing'
imooc = 'imooc'
# 指定名字對(duì)應(yīng)的模板數(shù)據(jù)內(nèi)容
result = template.format(w = world, c = china, b = beijing, i = imooc)
print(result) # ==> Hello World, Hello China, Hello Beijing, Hello imooc.
請(qǐng)使用兩種format的方式打印字符串Life is short, you need Python
。
參考答案:
print('Life is short, you need {}'.format('Python'))
print('Life is short, you need {launguage}'.format( launguage = 'Python'))
請(qǐng)驗(yàn)證,完成請(qǐng)求
由于請(qǐng)求次數(shù)過多,請(qǐng)先驗(yàn)證,完成再次請(qǐng)求
打開微信掃碼自動(dòng)綁定
綁定后可得到
使用 Ctrl+D 可將課程添加到書簽
舉報(bào)