You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用termcolor时带颜色文本居中对齐异常的修复咨询

问题:带颜色文本与普通文本居中对齐不一致的修复方法

原代码意图让带颜色文本和普通文本在终端中居中显示:

import shutil
columns = shutil.get_terminal_size().columns
from termcolor import colored

col = colored("test", 'white', 'on_red')
print(f"This is a {col} run".center(columns))
print('this is a test run'.center(columns))

运行后两行文本垂直对齐偏移,实际输出示例:

This is a test run                                                   
                                                         this is a test run                                                          

问题原因

termcolor.colored()生成的字符串包含ANSI颜色控制码(终端识别颜色的隐形特殊字符),但Python的str.center()方法会将这些控制码计入字符串总长度,导致计算左右填充空格时,错误认为带颜色的字符串更长,最终填充空格更少,出现偏移。

修复方案

核心思路是计算字符串实际显示长度(剔除ANSI控制码),再手动计算左右填充空格数,实现精准居中。

实现代码

import shutil
import re
from termcolor import colored

# 获取终端宽度
columns = shutil.get_terminal_size().columns

# 计算字符串实际显示长度(移除ANSI控制码)
def get_display_length(s):
    ansi_pattern = re.compile(r'\x1B(?:[@-Z\\-_]|\[.*?[a-zA-Z])')
    return len(ansi_pattern.sub('', s))

# 生成带颜色的目标字符串
colored_text = colored("test", 'white', 'on_red')
full_colored_str = f"This is a {colored_text} run"

# 计算实际显示长度与左右填充空格
display_len = get_display_length(full_colored_str)
padding = (columns - display_len) // 2

# 输出带颜色的居中文本
print(' ' * padding + full_colored_str)
# 输出普通居中文本
print('this is a test run'.center(columns))

原理说明

  • 正则表达式r'\x1B(?:[@-Z\\-_]|\[.*?[a-zA-Z])'匹配并移除所有ANSI控制码,得到纯文本内容后计算的长度,才是终端实际显示的字符数。
  • 手动计算padding(左右填充空格数),确保填充空格数与普通文本center()方法的计算结果一致,实现垂直对齐。

内容的提问来源于stack exchange,提问作者say hello to the world

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 21:35:26