jazzband / prettytable

Display tabular data in a visually appealing ASCII table format
https://pypi.org/project/PrettyTable/
Other
1.36k stars 155 forks source link

Problem with termcolor + multi-line strings #187

Closed resposit closed 2 years ago

resposit commented 2 years ago

Hello,

I tried to create a table having one cell containing a colored multi-line string (using "\n" ). This seems to break the color of table borders. For example:

from prettytable import PrettyTable
from termcolor import colored
rows = [["A", colored("line1\nline2", 'red')]]
t = PrettyTable()
t.add_rows(rows)
print(t)

multiline

Everything is fine with a single-line colored string:

singleline

Is it a bug/feature or is there a better way to do this ? Thanks

hugovk commented 2 years ago

It's either a bug or not supported yet :)

A workaround is to apply the colour to the text before and after the newline, but not to the newline itself.

For example:

from prettytable import PrettyTable
from termcolor import colored
rows2 = [["A", colored("line1", "red") + "\n" +colored("line2", "red")]]
t2 = PrettyTable()
t2.add_rows(rows2)
print(t2)
image

Or with a helper:

from prettytable import PrettyTable
from termcolor import colored

def multiline_colored(text, color):
    lines = text.split("\n")
    lines = [colored(line, color) for line in lines]
    return "\n".join(lines)

rows3 = [["A", multiline_colored("line1\nline2", "red")]]
t3 = PrettyTable()
t3.add_rows(rows3)
print(t3)

Which could also be:

def multiline_colored(text, color):
    return "\n".join([colored(line, color) for line in text.split("\n")])
resposit commented 2 years ago

Thank you for the workaround, it works perfectly.