python-13-for循環(如何實現變量替換)


最后的代碼:

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'

  1. format 函數可以接受不限個參數,位置可以不按順序。

"{} {}".format("hello", "world") # 不設置指定位置,按默認順序
'hello world'

"{0} {1}".format("hello", "world") # 設置指定位置
'hello world'

"{1} {0} {1}".format("hello", "world") # 設置指定位置
'world hello world'

  1. 也可以設置參數

!/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" 是必須的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM