Python format() 相關使用網站
#格式化字串 限定字串長度 字數長度左邊補入空白
print(‘{:_>20}’.format(‘test’)) #output:________________test
#格式化字串 限定字串長度 字數長度右邊補入空白
print(‘{:_<20}’.format(‘test’)) #output:test________________
#格式化字串 限定字串長度 並將資料放置於至中位置 如無法至中則像右補入空白
print(‘{:_^20}’.format(‘test’)) #output:________test________
print(‘{:d}’.format(455))#455
print(‘{:05d}’.format(455)) #向左補0 output: 00455
print(‘{:f}’.format(455.555)) #output: 455.555000
print(‘{:5f}’.format(455.555))#向右補0 output: 455.555000
person={‘first’:’Jean-Luc’,’last’:’Picard’}
print(‘{p[first]} {p[last]}’.format(p=person)) #output: Jean-Luc Picard
data=[4,8,15,16,23,42]
print(‘{d[2]} || {d[4]}’.format(d=data)) #output: 15 || 23
#取得類別資料
class Plant(object):
type=’tree’
print(‘{p.type}’.format(p=Plant))
#output:tree
class Plant(object):
type=’tree’
kinds=[{‘name’:’oak’},{‘name’:’maple’}]
#取得屬性值 + 陣列物建的值
print(‘{p.type}:{p.kinds[0][name]}’.format(p=Plant))
#output: tree:oak
#————下面開始為Datatime相關的轉換——————#
from datetime import datetime,time #引入相關模組
print(‘{:%Y-%m-%d %H:%M}’.format(datetime(2001,2,3,4,5))) #時間格式 output:2001-02-03 04:05
print(‘{:%Y-%m-%d %H:%M}’.format(datetime.now())) #取出現在時間 並格式化 output:2018-05-17 15:28 <=時間非固定

Leave a Comment