027 python字串格式化
阿新 • • 發佈:2022-04-19
1. 在python語言中有多少種格式化字串的方法?
1. %格式化
2. 模板字串
3. 字串的format方法
4. fstring
2. 請解釋什麼是模板字串,如何使用?
通過Template物件封裝 $放置一些佔位符,並通過substitute方法用實際的值替換這些佔位符
from string import Template template1 = Template('$s是我最喜歡的程式語言,$s非常容易學校,而且功能強大') print(template1.substitute(s = 'Python')) print(template1.substitute(s = 'PHP')) template2 = Template('$hello world') print(template2.substitute(hello = 'abc')) # {}命名 template2 = Template('${h}ello world') print(template2.substitute(h = 'abc')) # $$ 輸出$ template3 = Template('$dollar$$相當於多少$pounds英鎊') print(template3.substitute(dollar=20, pounds=16)) # 使用字典傳參 data = {} data['dollar'] = 30 data['pounds'] = 25 print(template3.substitute(data))
Python是我最喜歡的程式語言,Python非常容易學校,而且功能強大
PHP是我最喜歡的程式語言,PHP非常容易學校,而且功能強大
abc world
abcello world
20$相當於多少16英鎊
30$相當於多少25英鎊