1. 在Python 語言中有多少中格式化字符串的方法?
- % 格式化
- 模板字符串
- 字符串的 format 方法
- fstring
2. 請解釋什麼是模板字符串,如何使用?
from string import Template
template1 = Template('$s是世界上最好的編程語言, $s非常容易學習,而且功能強大')
print(template1.substitute(s = 'Python'))
print(template1.substitute(s = 'PHP'))
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非常容易學習,而且功能強大
20$相當於多少16英鎊
30$相當於多少25英鎊
template2 = Template('${h}ello world')
print(template2.substitute(h = 'abc'))
abcello world
28 - 使用fstring 方法格式化字符串