Python中提供了多種格式化字符串的方式,遇到一個項目,在一個文件中,就用了至少兩種方式。特別是在使用Log時,更讓人迷惑。html
所以特意花時間來了解一下Python中字符串格式化的幾種方式:python
# -*- coding: utf-8 -*- import unittest class StringFormatTests(unittest.TestCase): def test_C_style(self): """ % 是老風格的字符串格式化方式, 也稱爲C語言風格,語法以下: %[(name)][flags][width].[precision]type name: 是佔位符名稱 flags: 可取值有: - 左對齊(默認右對齊) 0 表示使用0填充(默認填充是空格) width: 表示顯示寬度 precision:表示精度,即小數點後面的位數 type: %s string,採用str()顯示 %r string,採用repr()顯示 %c char %b 二進制整數 %d, %i 十進制整數 %o 八進制整數 %x 十六進制整數 %e 指數 %E 指數 %f, %F 浮點數 %% 表明字符‘%’ 注意,若是內容中包括%,須要使用%%來替換 :return: """ # 測試 flag 與 width print("%-10x" % 20) print("%-10x" % 20) print("%10x" % 20) print("%010x" % 20) # 測試 name的用法: print("hello, %s, my name is %s, age is %d" % ("lucy", "zhangsan", 20)) print("hello, %(yname)s, my name is %(myname)s, age is %(myage)d" % {"yname":"lucy", "myname":"zhangsan", "myage":20}) def test_new_style_format(self): """ string.format() 提供了新風格的格式化, 語法格式:{:format_spec} format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type] fill ::= <any character> align ::= "<" | ">" | "=" | "^" 對齊方式,分別是左、右、兩邊、中間對齊 sign ::= "+" | "-" | " " width ::= integer precision ::= integer type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%" ,默認值是 "s" 詳情參見:https://docs.python.org/2/library/string.html 由於{}要做爲格式化的標誌位,因此內容儘可能不要使用'{'或'}' 另外,能夠使用索引 相比而言,新風格的比老風格的強大太多了。 :return: """ print('hello, {0}, {2}, {1}'.format('a', 'b', 'c')) def test_template(self): """這種風格的,能夠看做是相似於Linux變量風格的 ${var} $var $$ 表明單個字符 '$' """ from string import Template s = Template('$who likes $what') print(s.substitute(who='tim', what='kung pao')) pass if __name__ =="main": unittest.main()