python中string格式化

python中可以对string, int, float等数据类型进行格式化操作。下面举例来说明一些常用操作。

先贴出 python 对 String Formatting Operations 讲解的连接,后面的例子和内容都以它为参考。

- flags

'#' :

'0' : 用'0'进行填充

'-'  : 左对齐

' '  : 对于数字来说,整数前面会有个空格,负数不收到影响

'+' : 对数字添加正负号

- conversion list

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方法。文档在这里,只是使用形式不一样,内容几乎一致。

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
原文地址:https://www.cnblogs.com/chen-kh/p/7251648.html