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.