python--格式化打印

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 textwrap
s = '''Her first attempts at usefulness were in an endeavour to find out who
were the parents, but Harriet could not tell.  She was ready to tell
every thing in her power, but on this subject questions were vain.
Emma was obliged to fancy what she liked--but she could never
believe that in the same situation _she_ should not have discovered
the truth.  Harriet had no penetration.  She had been satisfied
to 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 were
in an endeavour to find out who were the
parents, but Harriet could not tell.
She was ready to tell every thing in her
power, but on this subject questions
were vain. Emma was obliged to fancy
what she liked--but she could never
believe that in the same situation _she_
should not have discovered the truth.
Harriet had no penetration.  She had
been satisfied to hear and believe just
what Mrs. Goddard chose to tell her; and
looked no farther.





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值