1

I have a couple of fields I'd like to print, and if one of those fields hits a value, I'd like to print in red to warn.

I have some code to render in red that I cribbed from any number of SO posts (eg)

def warning_text(text):
     CRED = '\033[31m'
     CEND = '\033[m'
     return CRED + text + CEND

Largely it works

>>> print('test')
test
>>> print(warning_text('test'))
test

(imagine that second test is in red, I can't find the formatting to make it work)

But when I apply formatting, the red remains, but the formatting is lost:

>>> print('{:>9}{:>9}'.format('test','test'))
     test     test
>>> print('{:>9}{:>9}'.format('test',warning_text('test')))
     testtest

(again, the second test in line 4 is red but I can't work out how to format this text)

I've tried other options for the function like this:

>>> def warning_text(text):
...      CRED = '\033[31m'
...      CEND = '\033[m'
...      return '{} {} {}'.format(CRED,text,CEND)

without success.

What am I doing wrong?

martineau
  • 119,623
  • 25
  • 170
  • 301
datakid
  • 2,293
  • 5
  • 23
  • 35
  • 3
    The formatting interprets the ANSI codes as usual printable characters. So the red "test" consists of 5+4+3=12 characters and the formatting algorithm concludes that it shouldn't be prefixed with spaces to adjust it to the right. – Michael Butscher Oct 12 '20 at 00:22
  • This is the correct answer. I am slapping my head in embarrassment. – datakid Oct 12 '20 at 00:27

0 Answers0