python--格式化打印

来源:互联网 发布:easybcd修复linux引导 编辑:程序博客网 时间:2024/05/14 14:15

1.字符串方法(ljust,rjust,center,format)

>>> s='格式化打印'>>> print(s.ljust(40,'-'))'格式化打印-----------------------------------'>>> print(s.rjust(40,'-'))-----------------------------------格式化打印>>> print(s.center(40,'-'))-----------------格式化打印------------------
>>> print('{0:-^{1}}'.format(s,40))-----------------格式化打印------------------

2.format函数

>>> print(format(s,'-^40'))-----------------格式化打印------------------>>> print(format(s,'->40'))-----------------------------------格式化打印>>> print(format(s,'-<40'))格式化打印-----------------------------------

使用format函数的好处是,他不仅适用于字符串,还可以格式化数字等类型:

>>> s=123>>> format(s,'->40')'-------------------------------------123'
>>> x = 1234.56789>>> print(format(x,'.2f'))1234.57
>>> x = 1234.56789>>> print(format(x,',.2f'))1,234.57

3.textwrap模块

优点:长(多行)字符串指定列宽。

import textwraps = '''Her first attempts at usefulness were in an endeavour to find out whowere the parents, but Harriet could not tell.  She was ready to tellevery thing in her power, but on this subject questions were vain.Emma was obliged to fancy what she liked--but she could neverbelieve that in the same situation _she_ should not have discoveredthe truth.  Harriet had no penetration.  She had been satisfiedto hear and believe just what Mrs. Goddard chose to tell her;and looked no farther.'''print(textwrap.fill(s,40,initial_indent='  '))

打印效果:

>>> runfile('E:/桌面/代码池/untitled1.py', wdir='E:/桌面/代码池')  Her first attempts at usefulness werein an endeavour to find out who were theparents, but Harriet could not tell.She was ready to tell every thing in herpower, but on this subject questionswere vain. Emma was obliged to fancywhat she liked--but she could neverbelieve that in the same situation _she_should not have discovered the truth.Harriet had no penetration.  She hadbeen satisfied to hear and believe justwhat Mrs. Goddard chose to tell her; andlooked no farther.





0 0
原创粉丝点击