Search code examples
pythonlatexpylatex

How to remove the @-expressions in a booktabs table created by pylatex?


This code:

from pylatex import (
    Tabular, 
)

# make tabular
doc = Tabular('lcc', booktabs=True)
doc.add_row('A','B','C')
doc.add_hline()
doc.add_row((1, 2, 3))

doc.generate_tex("my_table")

produces my_table.tex:

\begin{tabular}{@{}lcc@{}}%
\toprule%
A&B&C\\%
\midrule%
1&2&3\\\bottomrule%
%
\end{tabular}

As you can seen, in the tabular parameter, the column alignments are preceded and followed by @{}.
It doesn't happen if I don't use booktabs=True, but I need this option to add \toprule, \midrule and \bottomrule.

How can I avoid the @{}s?


Solution

  • Instead of removing them, add more @{...}. Sounds strange, but you can use them to add the default column padding back:

    from pylatex import (
        Tabular, 
    )
    
    # make tabular
    doc = Tabular('@{\\hspace{\\tabcolsep}}lcc@{\\hspace{\\tabcolsep}}', booktabs=True)
    doc.add_row('A','B','C')
    doc.add_hline()
    doc.add_row((1, 2, 3))
    
    doc.generate_tex("my_table")
    

    Alternatively, use a tabularx and embrace the @{}. It will ensure that the text in the tabularx will nicely align with the surrounding text:

    from pylatex import (
        Tabularx, 
    )
    
    # make tabular
    doc = Tabularx('XXX', booktabs=True)
    doc.add_row('A','B','C')
    doc.add_hline()
    doc.add_row((1, 2, 3))
    
    doc.generate_tex("my_table")