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

查看:333
本文介绍了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语句),则所有内容都会按预期打印.
  • 但是::如果我尝试使每一列在一行中具有不同的颜色,则对齐方式将被抛出.从技术上讲,会保留 alignment 填充字符(空格)未按要求打印;实际上,填充字符似乎已被完全删除.
  • 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.

我已经通过 colorama

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天全站免登陆