Python 的 `str.format()`、填充字符和 ANSI 颜色 [英] Python’s `str.format()`, fill characters, and ANSI colors

查看:25
本文介绍了Python 的 `str.format()`、填充字符和 ANSI 颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 2 中,我使用 str.format() 来对齐我打印到终端的一堆文本列.基本上,它是一个表格,但我没有打印任何边框或任何东西——它只是文本行,对齐到列中.

In Python 2, I’m using str.format() to align a bunch of columns of text I’m printing to a terminal. Basically, it’s a table, but I’m not printing any borders or anything—it’s simply rows of text, aligned into columns.

  • 没有任何色彩摆弄,一切都按预期打印.
  • 如果我用 ANSI 颜色代码包装一整行(即一个 print 语句),一切都会按预期打印.
  • 但是:如果我尝试将一行中的每一列设置为不同的颜色,对齐就会被取消.从技术上讲,保留了对齐填充字符(空格)没有按预期打印;事实上,填充字符似乎被完全删除了.
  • With no color-fiddling, everything prints as expected.
  • If I wrap an entire row (i.e., one print statement) with ANSI color codes, everything prints as expected.
  • However: If I try to make each column a different color within a row, the alignment is thrown off. Technically, the alignment is preserved; it’s the fill characters (spaces) that aren’t printing as desired; in fact, the fill characters seem to be completely removed.

我已经用 coloramaxtermcolor.结果是一样的.因此,我确定问题与 str.format() 与字符串中间的 ANSI 转义序列不兼容.

I’ve verified the same issue with both colorama and xtermcolor. The results were the same. Therefore, I’m certain the issue has to do with str.format() not playing well with ANSI escape sequences in the middle of a string.

但是我不知道该怎么办!:(我真的很想知道这个问题是否有任何解决方法.

But I don’t know what to do about it! :( I would really like to know if there’s any kind of workaround for this problem.

颜色和对齐是提高可读性的有力工具,可读性是软件可用性的重要组成部分.如果无需手动对齐每列文本即可完成此操作,这对我来说意义重大.

Color and alignment are powerful tools for improving readability, and readability is an important part of software usability. It would mean a lot to me if this could be accomplished without manually aligning each column of text.

帮助不大?☺

推荐答案

Python 不区分正常"字符和 ANSI 颜色代码,它们也是终端解释的字符.

Python doesn't distinguish between 'normal' characters and ANSI colour codes, which are also characters that the terminal interprets.

换句话说,将 'x1b[92m' 打印到终端可能会改变终端文本颜色,Python 不认为这是一组 5 个字符.如果使用 print repr(line) 代替,python 将打印字符串文字形式,包括对非 ASCII 可打印字符使用转义码(因此 ESC ASCII 码 27 显示为 x1b) 以查看添加了多少.

In other words, printing 'x1b[92m' to a terminal may change the terminal text colour, Python doesn't see that as anything but a set of 5 characters. If you use print repr(line) instead, python will print the string literal form instead, including using escape codes for non-ASCII printable characters (so the ESC ASCII code, 27, is displayed as x1b) to see how many have been added.

您需要手动调整列对齐方式以允许使用这些额外字符.

You'll need to adjust your column alignments manually to allow for those extra characters.

如果没有您的实际代码,我们很难为您提供帮助.

Without your actual code, that's hard for us to help you with though.

这篇关于Python 的 `str.format()`、填充字符和 ANSI 颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆