上一篇文章: Python实用技法第31篇:文本过滤和清理
下一篇文章: Python实用技法第33篇:字符串链接及合并
咱们须要以某种对齐方式将文本作格式化处理。html
对于基本的字符串对齐要求,能够使用字符串的ljust()、rjust()和center()方法。示例以下:python
>>> text = 'Hello World' >>> text.ljust(20) 'Hello World ' >>> text.rjust(20) ' Hello World' >>> text.center(20) ' Hello World ' >>>
全部这些方法均可接受一个可选的填充字符。例如:segmentfault
>>> text.rjust(20,'=') '=========Hello World' >>> text.center(20,'*') '****Hello World*****' >>>
format()函数也能够用来轻松完成对齐的任务。须要作的就是合理利用'<'、'>',或'^'字符以及一个指望的宽度值[2]。例如:函数
>>> format(text, '>20') ' Hello World' >>> format(text, '<20') 'Hello World ' >>> format(text, '^20') ' Hello World ' >>>
若是想包含空格以外的填充字符,能够在对齐字符以前指定:code
>>> format(text, '=>20s') '=========Hello World' >>> format(text, '*^20s') '****Hello World*****' >>>
当格式化多个值时,这些格式化代码也能够用在format()方法中。例如:orm
>>> '{:>10s} {:>10s}'.format('Hello', 'World') ' Hello World' >>>
format()的好处之一是它并非特定于字符串的。它能做用于任何值,这使得它更加通用。例如,能够对数字作格式化处理:htm
>>> x = 1.2345 >>> format(x, '>10') ' 1.2345' >>> format(x, '^10.2f') ' 1.23 '
在比较老的代码中,一般会发现%操做符用来格式化文本。例如:对象
>>> '%-20s' % text 'Hello World ' >>> '%20s' % text ' Hello World'
可是在新的代码中,咱们应该会更钟情于使用format()函数或方法。format()比%操做符提供的功能要强大多了。此外,format()可做用于任意类型的对象,比字符串的ljust()、rjust()以及center()方法要更加通用。字符串
想了解format()函数的全部功能,请参考Python的在线手册http://docs.python.org/3/libr... string. html#formatspec。get
上一篇文章: Python实用技法第31篇:文本过滤和清理
下一篇文章: Python实用技法第33篇:字符串链接及合并