如何用Python的textwrap库将字符串固定为指定宽度?
解决textwrap生成固定宽度文本的问题
textwrap库本身没有直接让每行强制填充到指定宽度的配置项,默认只会拆分长文本,短行不会补空格,这就是你表格宽度不一致的原因。
解决思路很简单:先把文本拆分成每行的列表,再给每行补空格到指定宽度,最后再组合成字符串放进表格里。
修改后的代码如下:
from tabulate import tabulate import textwrap tabulate.PRESERVE_WHITESPACE = True # 测试用字符串(可替换为你提供的任意测试文本) s = "Meta 335 to 95\n\nAmzn 188 to 96\n\nNflx 700 to 286\n\nSpot 305 to 80\n\nCRM 311 to 160\n\nSnap 57 to 10\n\nAmd 164 to 60\n\nARKK 126 to 39\n\nThese are all stocks off their Nov 2021 highs. Most of the market was poor phrasing, but this is some good perspective (instead of comparing vs the indices)" width = 64 # 先拆分文本为每行列表,保留原有配置参数 lines = textwrap.wrap( s, width, replace_whitespace=False, break_long_words=True, break_on_hyphens=False, ) # 给每行补空格到指定宽度,这里用左对齐填充,可换成center/rjust调整对齐方式 fixed_width_lines = [line.ljust(width) for line in lines] # 重新组合成带固定宽度的字符串 s_fixed = '\n'.join(fixed_width_lines) print(tabulate([[s_fixed]], tablefmt="grid"))
这样处理后,不管原文本的行长短,每行都会被填充到设定的64个字符宽度,表格的grid边框会保持一致宽度,打印多个文本框时格式就协调了。另外原字符串里的手动换行(比如\n\n)会被保留,补空格后空行也会变成对应宽度的空格行,不会破坏格式。
内容的提问来源于stack exchange,提问作者Jon
相关产品推荐
相关产品推荐

