码迷,mamicode.com
首页 > 编程语言 > 详细

【python cookbook】【字符串与文本】13.对齐文本字符串

时间:2016-08-21 19:57:01      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

问题:以某种对齐方式将文本做格式化处理

解决方案:

1、针对字符串:ljust()、rjust()、center()方法

2、针对任何值,更加通用的:format()  更多内容:https://docs.python.org/3/library/string.html#formatspec

>>> text=Hello World
>>> text.ljust(20)
Hello World         
>>> text.rjust(20)
         Hello World
>>> text.center(20)
    Hello World     
>>> text.ljust(20,=)
Hello World=========
>>> text.rjust(20,*)
*********Hello World
>>> text.center(20,+)
++++Hello World+++++
>>> 

format():

格式限定符

它有着丰富的的“格式限定符”(语法是{}中带:号),比如:

填充与对齐
填充常跟对齐一起使用
^、<、>分别是居中、左对齐、右对齐,后面带宽度
:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充

精度与类型f
精度常跟类型f一起使用

其他类型
主要就是进制了,b、d、o、x分别是二进制、十进制、八进制、十六进制。

用,号还能用来做金额的千位分隔符。

技术分享

技术分享

>>> format(text,>20)
         Hello World
>>> format(text,<20)
Hello World         
>>> format(text,^20)
    Hello World     
>>> format(text,*>20)  #空格外的其他填充字符可以在对齐字符之前指定
*********Hello World
>>> format(text,=<20)
Hello World=========
>>> format(text,%^20)
%%%%Hello World%%%%%
>>> #当格式化多个值时,格式化代码代码可以用在format()方法中
>>> {:>10} {:>10}.format(Hello,World)
     Hello      World
>>> {:>10} {:%^10}.format(Hello‘,World)
     Hello %%World%%%>>> {:#<10} {:%^10}.format(Hello‘,World)
Hello##### %%World%%%
>>> {:<20}.format(Hello World)
Hello World         
>>> {:*<20}.format(Hello World)
Hello World*********
>>> {:^20}.format(Hello World)
    Hello World     
>>> 

 

【python cookbook】【字符串与文本】13.对齐文本字符串

标签:

原文地址:http://www.cnblogs.com/apple2016/p/5793287.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!