Python中有3種format字符串的方式:html
和c語言裏面的 sprintf 相似,參數格式也同樣python
title = "world" year = 2013 print "hello %s, %10d" % (title, year)
這種方式有一個陷阱,好比 title 是一個list,執行語句 "hello %s" % title,會觸發一個異常;正確的作法是先把 title 轉換爲 string,或用 string.formatspa
title = "world" year = 2013 print "hello %(title)s, %(year)10d" % {"title":title, "year":year}
string.format 也支持命名參數:code
"hello {title}, {year}".format(title=title, year=year) "hello {title}, {year}".format(**{"title":title, "year":year})
string.format還有一個地方須要注意,若是參數是unicode,則string也必須是unicode,不然,會觸發異常。如執行下述語句會出錯:orm
title = u"標題黨" "hello {0}".format(title)
title = "world" year = 2013 print "hello {0}, {1}".format(title, year) print "today is {0:%Y-%m-%d}".format(datetime.datetime.now())
string.format 比 % 格式化方式更優雅,不容易出錯htm