在編寫程序的過程中,經常需要進行格式化輸出,每次用每次查。乾脆就在這裏整理一下,以便索引。
格式化操作符(%)
"%"是Python風格的字符串格式化操作符,非常類似C語言裏的printf()函數的字符串格式化(C語言中也是使用%)。
下面整理了一下Python中字符串格式化符合:
格式化符號 |
說明 |
%c |
轉換成字符(ASCII 碼值,或者長度爲一的字符串) |
%r |
優先用repr()函數進行字符串轉換 |
%s |
優先用str()函數進行字符串轉換 |
%d / %i |
轉成有符號十進制數 |
%u |
轉成無符號十進制數 |
%o |
轉成無符號八進制數 |
%x / %X |
轉成無符號十六進制數(x / X 代表轉換後的十六進制字符的大小寫) |
%e / %E |
轉成科學計數法(e / E控制輸出e / E) |
%f / %F |
轉成浮點數(小數部分自然截斷) |
%g / %G |
%e和%f / %E和%F 的簡寫 |
%% |
輸出% (格式化字符串裏面包括百分號,那麼必須使用%%) |
這裏列出的格式化符合都比較簡單,唯一想要強調一下的就是"%s"和"%r"的差別。
看個簡單的代碼:
string = "Hello\tWill\n" print "%s" %string print "%r" %string
代碼的輸出爲:
其實,這裏的差異是str()和repr()兩個內建函數之間的差異:
- str()得到的字符串是面向用戶的,具有較好的可讀性
-
repr()得到的字符串是面向機器的
- 通常(不是所有)repr()得到的效果是:obj == eval(repr(obj))
格式化操作符輔助符
通過"%"可以進行字符串格式化,但是"%"經常會結合下面的輔助符一起使用。
輔助符號 |
說明 |
* |
定義寬度或者小數點精度 |
- |
用做左對齊 |
+ |
在正數前面顯示加號(+) |
# |
在八進制數前面顯示零(0),在十六進制前面顯示"0x"或者"0X"(取決於用的是"x"還是"X") |
0 |
顯示的數字前面填充"0"而不是默認的空格 |
(var) |
映射變量(通常用來處理字段類型的參數) |
m.n |
m 是顯示的最小總寬度,n 是小數點後的位數(如果可用的話) |
看一些簡單的 例子:
num = 100 print "%d to hex is %x" %(num, num) print "%d to hex is %X" %(num, num) print "%d to hex is %#x" %(num, num) print "%d to hex is %#X" %(num, num) # 浮點數 f = 3.1415926 print "value of f is: %.4f" %f # 指定寬度和對齊 students = [{"name":"Wilber", "age":27}, {"name":"Will", "age":28}, {"name":"June", "age":27}] print "name: %10s, age: %10d" %(students[0]["name"], students[0]["age"]) print "name: %-10s, age: %-10d" %(students[1]["name"], students[1]["age"]) print "name: %*s, age: %0*d" %(10, students[2]["name"], 10, students[2]["age"]) # dict參數 for student in students: print "%(name)s is %(age)d years old" %student
代碼輸出爲:
對於Python的格式化操作符,不僅可以接受tuple類型的參數,也可以支持dict,象上面代碼的最後一部分,那麼格式化字符串中就可以直接使用"%(key)s"(這裏的s根據具體類型改變)的方式表示dict中對應的value了。
字符串模板
其實,在Python中進行字符串的格式化,除了格式化操作符,還可以使用string模塊中的字符串模板(Template)對象。下面就主要看看Template對象的substitute()方法:
from string import Template s = Template("Hi, $name! $name is learning $language") print s.substitute(name="Wilber", language="Python") d = {"name": "Will", "language": "C#"} print s.substitute(d) # 用$$表示$符號 s = Template("This book ($bname) is 17$$") print s.substitute(bname="TCP/IP")
代碼結果爲:
字符串內建函數format()
Python2.6開始,新增了一種格式化字符串的函數str.format(),通過這個函數同樣可以對字符串進行格式化處理。在format()函數中,使用“{}”符號來當作格式化操作符。
下面直接通過一些簡單的例子演示format()函數的基本使用:
# 位置參數 print "{0} is {1} years old".format("Wilber", 28) print "{} is {} years old".format("Wilber", 28) print "Hi, {0}! {0} is {1} years old".format("Wilber", 28) # 關鍵字參數 print "{name} is {age} years old".format(name = "Wilber", age = 28) # 下標參數 li = ["Wilber", 28] print "{0[0]} is {0[1]} years old".format(li) # 填充與對齊 # ^、<、>分別是居中、左對齊、右對齊,後面帶寬度 # :號後面帶填充的字符,只能是一個字符,不指定的話默認是用空格填充 print '{:>8}'.format('3.14') print '{:<8}'.format('3.14') print '{:^8}'.format('3.14') print '{:0>8}'.format('3.14') print '{:a>8}'.format('3.14') # 浮點數精度 print '{:.4f}'.format(3.1415926) print '{:0>10.4f}'.format(3.1415926) # 進制 # b、d、o、x分別是二進制、十進制、八進制、十六進制 print '{:b}'.format(11) print '{:d}'.format(11) print '{:o}'.format(11) print '{:x}'.format(11) print '{:#x}'.format(11) print '{:#X}'.format(11) # 千位分隔符 print '{:,}'.format(15700000000)
str的內建函數
在最開始的時候,Python有一個專門的string模塊,要使用string的方法要先import這個模塊。從Python2.0開始, 爲了方便使用,str類型添加了很多內建函數,這些函數可以實現跟string模塊中函數相同的功能,也就是說,只要S是一個字符串對象就可以直接使用內建函數,而不用import。
對於字符串的格式化處理,也可以考慮使用str的其他內建函數:
>>> dir(str) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__get slice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mo d__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook __', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index ', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', ' rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', ' strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
下面整理出來了一些常用的str類型的內建函數:
# 小寫 S.lower() # 大寫 S.upper() #大小寫互換 S.swapcase() # 首字母大寫 S.capitalize() # 輸出width個字符,S左對齊,不足部分用fillchar填充,默認的爲空格。 S.ljust(width,[fillchar]) # 右對齊 S.rjust(width,[fillchar]) # 中間對齊 S.center(width, [fillchar]) # 返回S中出現substr的第一個字母的標號,如果S中沒有substr則返回-1。start和end作用就相當於在S[start:end]中搜索 S.find(substr, [start, [end]]) # 返回S中最後出現的substr的第一個字母的標號,如果S中沒有substr則返回-1,也就是說從右邊算起的第一次出現的substr的首字母標號 S.rfind(substr, [start, [end]]) # 計算substr在S中出現的次數 S.count(substr, [start, [end]]) #把S中的oldstar替換爲newstr,count爲替換次數 S.replace(oldstr, newstr, [count]) # 把S中前後chars中有的字符全部去掉,可以理解爲把S前後chars替換爲None S.strip([chars]) S.lstrip([chars]) S.rstrip([chars]) # 以sep爲分隔符,把S分成一個list。maxsplit表示分割的次數。默認的分割符爲空白字符 S.split([sep, [maxsplit]]) # 把seq代表的字符串序列,用S連接起來 S.join(seq)
總結
本文整理了一些格式化字符,以及一些輔助指令,結合格式化操作符(%),就可以生成特定格式的字符串了。也可以使用字符串模板來進行字符串格式化。