最后的代碼:
chinese_zodiac = "猴雞狗豬鼠牛虎兔龍蛇馬羊"
for year in range(2000,2019):
print("{} 的生肖是 {}".format(year,chinese_zodiac[year%12]))
https://www.runoob.com/python/att-string-format.html
Python2.6 開始,新增了一種格式化字符串的函數 str.format(),它增強了字符串格式化的功能。
基本語法是通過 {} 和 : 來代替以前的 % 。
format 函數可以接受不限個參數,位置可以不按順序。
"{} {}".format("hello", "world") # 不設置指定位置,按默認順序
'hello world'
"{0} {1}".format("hello", "world") # 設置指定位置
'hello world'
"{1} {0} {1}".format("hello", "world") # 設置指定位置
'world hello world'
- format 函數可以接受不限個參數,位置可以不按順序。
"{} {}".format("hello", "world") # 不設置指定位置,按默認順序
'hello world'
"{0} {1}".format("hello", "world") # 設置指定位置
'hello world'
"{1} {0} {1}".format("hello", "world") # 設置指定位置
'world hello world'
- 也可以設置參數
!/usr/bin/python
-- coding: UTF-8 --
print("網站名:{name}, 地址 {url}".format(name="菜鳥教程", url="www.runoob.com"))
通過字典設置參數
site = {"name": "菜鳥教程", "url": "www.runoob.com"}
print("網站名:{name}, 地址 {url}".format(**site))
通過列表索引設置參數
my_list = ['菜鳥教程', 'www.runoob.com']
print("網站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必須的