27 - python字符串格式化

1. 在Python 語言中有多少中格式化字符串的方法?

  • % 格式化
  • 模板字符串
  • 字符串的 format 方法
  • fstring

2. 請解釋什麼是模板字符串,如何使用?

# 通過Template對象封裝 $放置一些佔位符,並通過substitute方法用實際的值替換這些佔位符
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 方法格式化字符串

發佈了128 篇原創文章 · 獲贊 128 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章