Search code examples
pythonrestructuredtext

What are some approaches to outputting a Python data structure to reStructuredText


I have a list of tuples in Python that I would like to output to a table in reStructuredText.

The docutils library has great support for converting reStructuredText to other formats, but I want to write directly from a data structure in memory to reStructuredText.


Solution

  • I'm not aware of any libraries to output RST from python data structures, but it's pretty easy to format it yourself. Here's an example of formatting a list of python tuples to an RST table:

    >>> data = [('hey', 'stuff', '3'),
                ('table', 'row', 'something'),
                ('xy', 'z', 'abc')]
    >>> numcolumns = len(data[0])
    >>> colsizes = [max(len(r[i]) for r in data) for i in range(numcolumns)]
    >>> formatter = ' '.join('{:<%d}' % c for c in colsizes)
    >>> rowsformatted = [formatter.format(*row) for row in data]
    >>> header = formatter.format(*['=' * c for c in colsizes])
    >>> output = header + '\n' + '\n'.join(rowsformatted) + '\n' + header
    >>> print output
    ===== ===== =========
    hey   stuff 3        
    table row   something
    xy    z     abc      
    ===== ===== =========