Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions tabulate/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1321,12 +1321,14 @@ def _format(val, valtype, floatfmt, intfmt, missingval="", has_invisible=True):
elif valtype is int:
if isinstance(val, str):
val_striped = val.encode("unicode_escape").decode("utf-8")
colored = re.search(r"(\\[xX]+[0-9a-fA-F]+\[\d+[mM]+)([0-9.]+)(\\.*)$", val_striped)
colored = re.search(
r"(\\[xX]+[0-9a-fA-F]+\[\d+[mM]+)([-+]?[0-9.]+)(\\.*)$", val_striped
)
if colored:
total_groups = len(colored.groups())
if total_groups == 3:
digits = colored.group(2)
if digits.isdigit():
if digits.isdigit() or (intfmt and digits.lstrip("+-").isdigit()):
val_new = colored.group(1) + format(int(digits), intfmt) + colored.group(3)
val = val_new.encode("utf-8").decode("unicode_escape")
intfmt = ""
Expand Down
32 changes: 32 additions & 0 deletions test/test_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -2871,6 +2871,38 @@ def test_intfmt_with_colors():
assert_equal(expected, formatted)


@mark.parametrize(
("value", "intfmt", "expected"),
[
("-1234", ",", "-1,234"),
("+1234", "+,", "+1,234"),
("-1234", "#x", "-0x4d2"),
("+1234", "#x", "0x4d2"),
("1234", ",", "1,234"),
("0", ",", "0"),
],
)
def test_intfmt_with_signed_colors(value, intfmt, expected):
"Integer formatting preserves ANSI colors around signed values."
colored = f"\x1b[31m{value}\x1b[0m"
result = tabulate([[colored]], intfmt=intfmt, tablefmt="plain")
assert_equal(f"\x1b[31m{expected}\x1b[0m", result)


@mark.parametrize("value", ["+1234", "-001234", "-0"])
def test_signed_colors_without_intfmt(value):
"An omitted format retains signed colored text as supplied."
colored = f"\x1b[31m{value}\x1b[0m"
assert_equal(colored, tabulate([[colored]], tablefmt="plain"))


def test_signed_colors_without_column_intfmt():
"A column without a requested format retains its signed colored text."
colored = "\x1b[31m+1234\x1b[0m"
result = tabulate([[1234, colored]], intfmt=[","], tablefmt="plain")
assert_equal(f"1,234 {colored}", result)


def test_empty_data_with_headers():
"Output: table with empty data and headers as firstrow"
expected = ""
Expand Down