5

I am using tabulate to pretty-print tables in Python 2.7. It does align anything that can be converted to an number nicely by decimal point and also supports truncation of digits after the decimal point. However, I need both of these capabilities when working with number strings that contain a suffix (e.g. 37.58 MiB).

import tabulate

fields = [['37.58 MiB', '42.2323 KiB'],
          ['0.12893 GiB', '8.012 MiB']]

print tabulate.tabulate(fields)

yields the output:

-----------  -----------
37.58 MiB    42.2323 KiB
0.12893 GiB  8.012 MiB
-----------  -----------

what I want is this:

-----------  -----------
37.58 MiB    42.23 KiB
 0.12 GiB     8.01 MiB
-----------  -----------

Is tabulate capable of achieving this?

Simon Fromme
  • 3,104
  • 18
  • 30
  • Read [here](https://pypi.python.org/pypi/tabulate#downloads). _You can override the default alignment with ``numalign`` and ``stralign`` named arguments. Possible column alignments are: ``right``, ``center``, ``left``, ``decimal`` (only for numbers), and ``None`` (to disable alignment)._ – CLeo-Dev Jul 06 '17 at 10:18
  • The string I want to align is `37.58 MiB` though which cannot be converted to a number (at least not by calling `float` on it, which I suspect tabular is doing) which the alignment `decimal` requires though. This is the whole point of the question. – Simon Fromme Jul 06 '17 at 10:21
  • 1
    The only solution I found is declaring `fields = [[37.58, "MiB", 42.2323, "KiB"], [0.12893, "GiB", 8.012, "MiB"]]` and then `print (tabulate.tabulate(fields, numalign="decimal"))`. The output is not as you want. – CLeo-Dev Jul 06 '17 at 10:31
  • That's certainly possible but not what I want. I just browsed through the `tabluate` source and suspect it is simply not possible. I might add this as a feature to the library at some point if I have time and other people think it's a good idea. – Simon Fromme Jul 06 '17 at 10:33

0 Answers0