python中能夠對string, int, float等數據類型進行格式化操做。下面舉例來講明一些經常使用操做。html
先貼出 python 對 String Formatting Operations 講解的鏈接,後面的例子和內容都以它爲參考。python
- flagsspa
'#' :orm
'0' : 用'0'進行填充htm
'-' : 左對齊blog
' ' : 對於數字來講,整數前面會有個空格,負數不收到影響文檔
'+' : 對數字添加正負號get
- conversion liststring
In[101]: print '%30.4fabc' % -1.23456 -1.2346abc In[102]: print '%30.4fabc' % -13345.3456 -13345.3456abc In[103]: print '%-30.4fabc' % -13345.3456 -13345.3456 abc In[104]: print '%-030.4fabc' % -13345.3456 -13345.3456 abc In[105]: print '%030.4fabc' % -13345.3456 -000000000000000000013345.3456abc In[106]: print '%30sabc' % 'hello,' hello,abc In[107]: print '%-30sabc' % 'hello,' hello, abc In[108]: print '% d' % -10 -10 In[109]: print '% d' % 10 10
In[111]: print("%#x" % -11) -0xb In[112]: print("%0x" % -11) -b
另一種格式化方式,使用str的format方法。文檔在這裏,只是使用形式不同,內容幾乎一致。io
In[125]: import datetime In[126]: print '{:-<30}abc'.format('left aligned') ...: print '{:~^30}abc'.format('centered') ...: print '{:*^30}'.format('centered') ...: print '{:+20f};{:+20f};{: 20f};{: 20f}'.format(3.14, -3.14, 3.14, -3.14) ...: print '{:<-20f};{:-20f}'.format(3.14, -3.14) ...: print "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42) ...: print "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42) ...: d = datetime.datetime(2010, 7, 4, 12, 15, 58) ...: print '{:%Y-%m-%d %H:%M:%S}'.format(d) ...: print '{text:*^30}{tail}'.format(text='abc',tail=123) ...: print '{:0=+30d}'.format(-10) ...: print '{:0>+30d}'.format(-10) left aligned------------------abc ~~~~~~~~~~~centered~~~~~~~~~~~abc ***********centered*********** +3.140000; -3.140000; 3.140000; -3.140000 3.140000 ; -3.140000 int: 42; hex: 2a; oct: 52; bin: 101010 int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010 2010-07-04 12:15:58 *************abc**************123 -00000000000000000000000000010 000000000000000000000000000-10