背景

在学习 python 的过程中,经常需要使用 print 函数打印一些信息以供交互。掌心悦目的对齐格式使得阅读更加舒心,有效缓解编程的枯燥。

一般解决方案

一般情况下,我们会使用 字符串的内置方法 ljust, center, rjust 等方法, 使用 format 也是常用的方法。以下是一个示例:

import textwrap
from DebugInfo.DebugInfo import *

width = 30

print(textwrap.fill('this', width).ljust(width), '|')
print(textwrap.fill('this is', width).ljust(width), '|')
print(textwrap.fill('this is a', width).ljust(width), '|')
print(textwrap.fill('this is a long', width).ljust(width), '|')

print(textwrap.fill('this', width).center(width), '|')
print(textwrap.fill('this is', width).center(width), '|')
print(textwrap.fill('this is a', width).center(width), '|')
print(textwrap.fill('this is a long', width).center(width), '|')

print()
print("{:>30s}".format('this'), '|')
print("{:>30s}".format('this is'), '|')
print("{:>30s}".format('this is a'), '|')
print("{:>30s}".format('this is a long'), '|')

这个代码演示了使用 textwrap 库 和 使用 format 两种方法对文本进行对齐打印,右侧的 ‘|’ 符号可以让我们看到对齐的效果,效果如下:
使用 textwrap 库 和 使用 format 两种方法对文本进行对齐打印
现在, 我们稍微调整一下上面的代码,使其中加入中文和全角字符,如下我们把第二行的 is 变为 is

import textwrap
from DebugInfo.DebugInfo import *

width = 30

print(textwrap.fill('this', width).ljust(width), '|')
print(textwrap.fill('this is', width).ljust(width), '|')
print(textwrap.fill('this 中国 a', width).ljust(width), '|')
print(textwrap.fill('this is a long', width).ljust(width), '|')

print(textwrap.fill('this', width).center(width), '|')
print(textwrap.fill('this is', width).center(width), '|')
print(textwrap.fill('this 中国 a', width).center(width), '|')
print(textwrap.fill('this is a long', width).center(width), '|')

print()
print("{:>30s}".format('this'), '|')
print("{:>30s}".format('this is'), '|')
print("{:>30s}".format('this 中国 a'), '|')
print("{:>30s}".format('this is a long'), '|')

修改后的代码运行打印如下:
对齐打印 全半角 中英文 混合字符串效果
很明显,在存在全/半角的第二行,中/英文的第三行,均出现了对不齐的现象。

DebugInfo 对齐方案

引入 DebugInfo 模块

pip install DebugInfo

我们使用 DebugInfo 修改上面的代码如下:

from DebugInfo.DebugInfo import *

# 创建一个 白板
白板 = 调试模板()
# 默认打印头为 |-, 一般不需要处理
白板.打印头 = ''

# 准备白板表格内容, 右侧添加一个 '|', 全球观察对齐的效果
白板.准备表格()
白板.添加一行('this', '|')
白板.添加一行('this is', '|')
白板.添加一行('this 中国 a', '|')
白板.添加一行('this is a long', '|')
白板.添加一行('-'*30, '|')

# 默认打印为左对齐
白板.展示表格(1)
# 符号 c 表示居中对齐
白板.设置列对齐('c').展示表格(1) 
# 符号 r 表示右对齐
白板.设置列对齐('r').展示表格(1)

上面的代码运行如下:
使用 DebugInfo 对齐打印 全半角 中英混合 字符串的效果
我们可以看到,在同样存在全/半角的第二行,中/英文的第三行,使用 DebugInfo 模块依然可以保持对齐打印效果。

小结

以上就是本次分享的使用DebugInfo模块进行全半角混合,中英混合字符串的左对齐, 居中对齐,右对齐 的打印效果。

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐