iT邦幫忙

DAY 23
0

Python初學起步走系列 第 23

[Python初學起步走-Day23] - str.format()

  • 分享至 

  • xImage
  •  

str.format()可以非常方便的建立字串

例如

#str_format.py
s = "The {0} {1} tower has {1} floors above ground and five underground.".format("taipei",101)
print(s) 

0的欄位會對應第一個參數,1的欄位會對應第二個參數....

而且可以連結字串與數字

也可以省略欄位名稱

例如

#str_format.py
s = "The {} {} tower has {} floors above ground and five underground.".format("taipei",101,101)
print(s)

欄位名稱也可以用關鍵字引數來給予

例如

#str_format.py
s = "The {location} {num} tower has {num} floors above ground and five underground.".format(num=101,location="taipei")
print(s)

群集資料型態利用索引來指定資料項

例如

#str_format.py
l = ["taipei","taichung","tainan",100,101,102]
s = "The {0[0]} {0[4]} tower has {0[4]} floors above ground and five underground.".format(l)
print(s)

dict(字典)型態

#str_format.py
d = {"city":"taipei","num":101}
s = "The {0[city]} {0[num]} tower has {0[num]} floors above ground and five underground.".format(d)
print(s)


上一篇
[Python初學起步走-Day22] - 模組(module)
下一篇
[Python初學起步走-Day24] - 物件導向(Object-oriented,OO) - 定義類別
系列文
Python初學起步走30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言