Python如何对齐字符串
作者:David Beazley 时间:2023-05-30 01:21:11
问题
你想通过某种对齐方式来格式化字符串
解决方案
对于基本的字符串对齐操作,可以使用字符串的 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()
同样可以用来很容易的对齐字符串。 你要做的就是使用 <,> 或者 ^ 字符后面紧跟一个指定的宽度。比如:
>>> 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()
方法更通用, 因为它可以用来格式化任意对象,而不仅仅是字符串。
如果想要完全了解 format()
函数的有用特性, 请参考 在线Python文档
来源:https://python3-cookbook.readthedocs.io/zh_CN/latest/c02/p13_aligning_text_strings.html
标签:Python,对齐,字符串
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python中将字典形式的数据循环插入Excel
2023-07-05 01:49:19
![](https://img.aspxhome.com/file/2023/4/135454_0s.png)
Python3调用微信企业号API发送文本消息代码示例
2023-05-03 16:23:41
对Python中创建进程的两种方式以及进程池详解
2021-05-21 14:37:48
Python中常见的异常总结
2021-11-15 04:21:27
python基于queue和threading实现多线程下载实例
2023-02-04 09:58:22
pytorch交叉熵损失函数的weight参数的使用
2021-02-27 15:52:31
![](https://img.aspxhome.com/file/2023/3/101703_0s.jpg)
华为校园招聘上机笔试题 扑克牌大小(python)
2021-11-25 23:54:22
keras获得model中某一层的某一个Tensor的输出维度教程
2023-12-15 11:28:54
pytorch 如何使用amp进行混合精度训练
2023-12-25 13:35:02
![](https://img.aspxhome.com/file/2023/0/88960_0s.jpg)
SQL Server 2008 清空删除日志文件(瞬间日志变几M)
2024-01-21 13:06:47
Golang使用CGO与Plugin技术运行加载C动态库
2024-02-05 06:20:27
MySQL5.7中的JSON基本操作指南
2024-01-27 20:38:34
理解CSS3线性渐变
2010-03-28 13:42:00
![](https://img.aspxhome.com/file/UploadPic/20103/28/01-27s.jpg)
简单的Python解密rsa案例
2022-05-28 07:30:18
![](https://img.aspxhome.com/file/2023/9/65109_0s.png)
SQL Server提示"选定的用户拥有对象,所以无法除去该用户”
2024-01-22 03:35:05
Python 绘图库 Matplotlib 入门教程
2021-07-21 00:22:07
![](https://img.aspxhome.com/file/2023/6/99166_0s.jpg)
单利模式及python实现方式详解
2021-07-21 21:45:15
Mysql如何查看表及字段信息
2024-01-28 21:35:43
![](https://img.aspxhome.com/file/2023/1/129931_0s.png)
asp随机生成文件名的函数
2009-02-11 13:41:00
Python使用tkinter库实现文本显示用户输入功能示例
2023-09-21 11:00:17
![](https://img.aspxhome.com/file/2023/1/105271_0s.gif)