Search code examples
pythonformattingtermcolor

Python: How to format the output from colored(var, 'color')


I'm currently outputting the term 'var' in my program, with the following formatting.

print(time,'\t{0:8f}\t'.format(var))

I've managed to output the var in color, depending on different conditions and I've got that to work, however, I can't format the output to the same formatting as above!

if(condition1==True):
  print(colored(var,'green'))

I've tried print(colored(var, 'green').format({0:8f})) and it hasn't worked. Does anyone know how to format colored outputs?


Solution

  • This works:

    var = 1.2345
    print(colored('\t{0:8f}\t'.format(var), 'green'))
    

    The idea is use format() to create the formatted string first, then feed that into colored().

    colored() wraps the given string in ASCII escape sequences that control the color. You can also do it like this:

    print(colored('\t{0:8f}\t', 'green').format(var))
    

    which passes the format string to colored() and then passes that to format() for variable substitution.