解决Python对齐文本字符串问题
作者:IT派森 时间:2021-08-20 10:22:26
问题
我们需要以某种对齐方式将文本做格式化处理。
解决方案
对于基本的字符串对齐要求,可以使用字符串的ljust()、rjust()和center()方法。示例如下:
>>> text = 'Hello World'
>>> text.ljust(20)
'Hello World '
>>> text.rjust(20)
' Hello World'
>>> text.center(20)
' Hello World '
>>>
所有这些方法都可接受一个可选的填充字符。例如:
>>> 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 '
>>>
如果想包含空格之外的填充字符,可以在对齐字符之前指定:
>>> format(text, '=>20s')
'=========Hello World'
>>> format(text, '*^20s')
'****Hello World*****'
>>>
当格式化多个值时,这些格式化代码也可以用在format()方法中。例如:
>>> '{:>10s} {:>10s}'.format('Hello', 'World')
' Hello World'
>>>
format()的好处之一是它并不是特定于字符串的。它能作用于任何值,这使得它更加通用。例如,可以对数字做格式化处理:
>>> 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()方法要更加通用。
总结
以上所述是小编给大家介绍的解决Python对齐文本字符串问题,网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
来源:https://www.jianshu.com/p/ea4ce8a6ff9d
标签:python,对齐,文本,字符串
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
VML模拟Rose画流程图代码
2008-09-02 10:58:00
![](https://img.aspxhome.com/file/UploadPic/20089/2/vml_rose_33s.gif)
scrapy与selenium结合爬取数据(爬取动态网站)的示例代码
2023-07-14 00:17:08
![](https://img.aspxhome.com/file/2023/7/79697_0s.png)
解决Python复杂zip文件的解压问题
2021-08-11 05:04:09
![](https://img.aspxhome.com/file/2023/9/75329_0s.jpg)
asp下为什么韩文字后面显示分号?
2011-03-10 11:07:00
JS 显示当前日期+星期(静态)
2007-09-11 13:29:00
php基于curl主动推送最新内容给百度收录的方法
2023-11-22 04:46:44
python实现Pyecharts实现动态地图(Map、Geo)
2021-01-21 11:33:58
![](https://img.aspxhome.com/file/2023/7/95897_0s.jpg)
浅谈Python的list中的选取范围
2023-06-23 01:58:01
新手常见6种的python报错及解决方法
2022-10-10 09:03:22
用实例说明python的*args和**kwargs用法
2021-05-04 08:25:55
python变量命名的7条建议
2021-05-15 20:16:07
ASP幻灯片
2009-09-04 18:05:00
Python简单实现的代理服务器端口映射功能示例
2022-09-10 07:52:54
![](https://img.aspxhome.com/file/2023/1/93711_0s.png)
解析:怎样掌握SQL Server中的数据查询
2009-01-19 13:30:00
深入理解Python虚拟机中元组(tuple)的实现原理及源码
2022-07-12 14:14:21
![](https://img.aspxhome.com/file/2023/0/79660_0s.png)
python实现整数的二进制循环移位
2022-09-08 23:11:39
![](https://img.aspxhome.com/file/2023/1/97681_0s.jpg)
python函数运行内存时间等性能检测工具
2021-04-08 02:24:00
![](https://img.aspxhome.com/file/2023/1/93801_0s.png)
Python中JSON的使用方法(超详细)
2023-11-15 23:04:19
![](https://img.aspxhome.com/file/2023/7/63947_0s.png)
python+django加载静态网页模板解析
2022-06-14 16:58:47
![](https://img.aspxhome.com/file/2023/4/97754_0s.png)
浅谈python输出列表元素的所有排列形式
2023-02-10 11:09:39