Coder Social home page Coder Social logo

jazzband / prettytable Goto Github PK

View Code? Open in Web Editor NEW
1.3K 23.0 147.0 531 KB

Display tabular data in a visually appealing ASCII table format

Home Page: https://pypi.org/project/PrettyTable/

License: Other

Python 100.00%
python package python-3 utility-library

prettytable's Introduction

PrettyTable

Jazzband PyPI version Supported Python versions PyPI downloads GitHub Actions status codecov Code style: Black

PrettyTable lets you print tables in an attractive ASCII form:

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide  | 1295 |  1158259   |      600.5      |
| Brisbane  | 5905 |  1857594   |      1146.4     |
| Darwin    | 112  |   120900   |      1714.7     |
| Hobart    | 1357 |   205556   |      619.5      |
| Melbourne | 1566 |  3806092   |      646.9      |
| Perth     | 5386 |  1554769   |      869.4      |
| Sydney    | 2058 |  4336374   |      1214.8     |
+-----------+------+------------+-----------------+

Installation

Install via pip:

python -m pip install -U prettytable

Install latest development version:

python -m pip install -U git+https://github.com/jazzband/prettytable

Or from requirements.txt:

-e git://github.com/jazzband/prettytable.git#egg=prettytable

Tutorial on how to use the PrettyTable API

Getting your data into (and out of) the table

Let's suppose you have a shiny new PrettyTable:

from prettytable import PrettyTable
table = PrettyTable()

and you want to put some data into it. You have a few options.

Row by row

You can add data one row at a time. To do this you can set the field names first using the field_names attribute, and then add the rows one at a time using the add_row method:

table.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
table.add_row(["Adelaide", 1295, 1158259, 600.5])
table.add_row(["Brisbane", 5905, 1857594, 1146.4])
table.add_row(["Darwin", 112, 120900, 1714.7])
table.add_row(["Hobart", 1357, 205556, 619.5])
table.add_row(["Sydney", 2058, 4336374, 1214.8])
table.add_row(["Melbourne", 1566, 3806092, 646.9])
table.add_row(["Perth", 5386, 1554769, 869.4])

All rows at once

When you have a list of rows, you can add them in one go with add_rows:

table.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
table.add_rows(
    [
        ["Adelaide", 1295, 1158259, 600.5],
        ["Brisbane", 5905, 1857594, 1146.4],
        ["Darwin", 112, 120900, 1714.7],
        ["Hobart", 1357, 205556, 619.5],
        ["Sydney", 2058, 4336374, 1214.8],
        ["Melbourne", 1566, 3806092, 646.9],
        ["Perth", 5386, 1554769, 869.4],
    ]
)

Column by column

You can add data one column at a time as well. To do this you use the add_column method, which takes two arguments - a string which is the name for the field the column you are adding corresponds to, and a list or tuple which contains the column data:

table.add_column("City name",
["Adelaide","Brisbane","Darwin","Hobart","Sydney","Melbourne","Perth"])
table.add_column("Area", [1295, 5905, 112, 1357, 2058, 1566, 5386])
table.add_column("Population", [1158259, 1857594, 120900, 205556, 4336374, 3806092,
1554769])
table.add_column("Annual Rainfall",[600.5, 1146.4, 1714.7, 619.5, 1214.8, 646.9,
869.4])

Mixing and matching

If you really want to, you can even mix and match add_row and add_column and build some of your table in one way and some of it in the other. Tables built this way are kind of confusing for other people to read, though, so don't do this unless you have a good reason.

Importing data from a CSV file

If you have your table data in a comma-separated values file (.csv), you can read this data into a PrettyTable like this:

from prettytable import from_csv
with open("myfile.csv") as fp:
    mytable = from_csv(fp)

Importing data from a database cursor

If you have your table data in a database which you can access using a library which confirms to the Python DB-API (e.g. an SQLite database accessible using the sqlite module), then you can build a PrettyTable using a cursor object, like this:

import sqlite3
from prettytable import from_db_cursor

connection = sqlite3.connect("mydb.db")
cursor = connection.cursor()
cursor.execute("SELECT field1, field2, field3 FROM my_table")
mytable = from_db_cursor(cursor)

Getting data out

There are three ways to get data out of a PrettyTable, in increasing order of completeness:

  • The del_row method takes an integer index of a single row to delete.
  • The del_column method takes a field name of a single column to delete.
  • The clear_rows method takes no arguments and deletes all the rows in the table - but keeps the field names as they were so you that you can repopulate it with the same kind of data.
  • The clear method takes no arguments and deletes all rows and all field names. It's not quite the same as creating a fresh table instance, though - style related settings, discussed later, are maintained.

Displaying your table in ASCII form

PrettyTable's main goal is to let you print tables in an attractive ASCII form, like this:

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide  | 1295 |  1158259   |      600.5      |
| Brisbane  | 5905 |  1857594   |      1146.4     |
| Darwin    | 112  |   120900   |      1714.7     |
| Hobart    | 1357 |   205556   |      619.5      |
| Melbourne | 1566 |  3806092   |      646.9      |
| Perth     | 5386 |  1554769   |      869.4      |
| Sydney    | 2058 |  4336374   |      1214.8     |
+-----------+------+------------+-----------------+

You can print tables like this to stdout or get string representations of them.

Printing

To print a table in ASCII form, you can just do this:

print(table)

The old table.printt() method from versions 0.5 and earlier has been removed.

To pass options changing the look of the table, use the get_string() method documented below:

print(table.get_string())

Stringing

If you don't want to actually print your table in ASCII form but just get a string containing what would be printed if you use print(table), you can use the get_string method:

mystring = table.get_string()

This string is guaranteed to look exactly the same as what would be printed by doing print(table). You can now do all the usual things you can do with a string, like write your table to a file or insert it into a GUI.

The table can be displayed in several different formats using get_formatted_string by changing the out_format=<text|html|json|csv|latex>. This function passes through arguments to the functions that render the table, so additional arguments can be given. This provides a way to let a user choose the output formatting.

def my_cli_function(table_format: str = 'text'):
  ...
  print(table.get_formatted_string(table_format))

Controlling which data gets displayed

If you like, you can restrict the output of print(table) or table.get_string to only the fields or rows you like.

The fields argument to these methods takes a list of field names to be printed:

print(table.get_string(fields=["City name", "Population"]))

gives:

+-----------+------------+
| City name | Population |
+-----------+------------+
| Adelaide  |  1158259   |
| Brisbane  |  1857594   |
| Darwin    |   120900   |
| Hobart    |   205556   |
| Melbourne |  3806092   |
| Perth     |  1554769   |
| Sydney    |  4336374   |
+-----------+------------+

The start and end arguments take the index of the first and last row to print respectively. Note that the indexing works like Python list slicing - to print the 2nd, 3rd and 4th rows of the table, set start to 1 (the first row is row 0, so the second is row 1) and set end to 4 (the index of the 4th row, plus 1):

print(table.get_string(start=1, end=4))

prints:

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Brisbane  | 5905 |    1857594 | 1146.4          |
| Darwin    | 112  |     120900 | 1714.7          |
| Hobart    | 1357 |     205556 | 619.5           |
+-----------+------+------------+-----------------+

Changing the alignment of columns

By default, all columns in a table are centre aligned.

All columns at once

You can change the alignment of all the columns in a table at once by assigning a one character string to the align attribute. The allowed strings are "l", "r" and "c" for left, right and centre alignment, respectively:

table.align = "r"
print(table)

gives:

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
|  Adelaide | 1295 |    1158259 |           600.5 |
|  Brisbane | 5905 |    1857594 |          1146.4 |
|    Darwin |  112 |     120900 |          1714.7 |
|    Hobart | 1357 |     205556 |           619.5 |
| Melbourne | 1566 |    3806092 |           646.9 |
|     Perth | 5386 |    1554769 |           869.4 |
|    Sydney | 2058 |    4336374 |          1214.8 |
+-----------+------+------------+-----------------+
One column at a time

You can also change the alignment of individual columns based on the corresponding field name by treating the align attribute as if it were a dictionary.

table.align["City name"] = "l"
table.align["Area"] = "c"
table.align["Population"] = "r"
table.align["Annual Rainfall"] = "c"
print(table)

gives:

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide  | 1295 |    1158259 |      600.5      |
| Brisbane  | 5905 |    1857594 |      1146.4     |
| Darwin    | 112  |     120900 |      1714.7     |
| Hobart    | 1357 |     205556 |      619.5      |
| Melbourne | 1566 |    3806092 |      646.9      |
| Perth     | 5386 |    1554769 |      869.4      |
| Sydney    | 2058 |    4336374 |      1214.8     |
+-----------+------+------------+-----------------+
Sorting your table by a field

You can make sure that your ASCII tables are produced with the data sorted by one particular field by giving get_string a sortby keyword argument, which must be a string containing the name of one field.

For example, to print the example table we built earlier of Australian capital city data, so that the most populated city comes last, we can do this:

print(table.get_string(sortby="Population"))

to get:

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Darwin    | 112  |   120900   |      1714.7     |
| Hobart    | 1357 |   205556   |      619.5      |
| Adelaide  | 1295 |  1158259   |      600.5      |
| Perth     | 5386 |  1554769   |      869.4      |
| Brisbane  | 5905 |  1857594   |      1146.4     |
| Melbourne | 1566 |  3806092   |      646.9      |
| Sydney    | 2058 |  4336374   |      1214.8     |
+-----------+------+------------+-----------------+

If we want the most populated city to come first, we can also give a reversesort=True argument.

If you always want your tables to be sorted in a certain way, you can make the setting long-term like this:

table.sortby = "Population"
print(table)
print(table)
print(table)

All three tables printed by this code will be sorted by population (you could do table.reversesort = True as well, if you wanted). The behaviour will persist until you turn it off:

table.sortby = None

If you want to specify a custom sorting function, you can use the sort_key keyword argument. Pass this a function which accepts two lists of values and returns a negative or positive value depending on whether the first list should appear before or after the second one. If your table has n columns, each list will have n+1 elements. Each list corresponds to one row of the table. The first element will be whatever data is in the relevant row, in the column specified by the sort_by argument. The remaining n elements are the data in each of the table's columns, in order, including a repeated instance of the data in the sort_by column.

Adding sections to a table

You can divide your table into different sections using the divider argument. This will add a dividing line into the table under the row who has this field set. So we can set up a table like this:

table = PrettyTable()
table.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
table.add_row(["Adelaide", 1295, 1158259, 600.5])
table.add_row(["Brisbane", 5905, 1857594, 1146.4])
table.add_row(["Darwin", 112, 120900, 1714.7])
table.add_row(["Hobart", 1357, 205556, 619.5], divider=True)
table.add_row(["Melbourne", 1566, 3806092, 646.9])
table.add_row(["Perth", 5386, 1554769, 869.4])
table.add_row(["Sydney", 2058, 4336374, 1214.8])

to get a table like this:

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
|  Adelaide | 1295 |  1158259   |      600.5      |
|  Brisbane | 5905 |  1857594   |      1146.4     |
|   Darwin  | 112  |   120900   |      1714.7     |
|   Hobart  | 1357 |   205556   |      619.5      |
+-----------+------+------------+-----------------+
| Melbourne | 1566 |  3806092   |      646.9      |
|   Perth   | 5386 |  1554769   |      869.4      |
|   Sydney  | 2058 |  4336374   |      1214.8     |
+-----------+------+------------+-----------------+

Any added dividers will be removed if a table is sorted.

Changing the appearance of your table - the easy way

By default, PrettyTable produces ASCII tables that look like the ones used in SQL database shells. But it can print them in a variety of other formats as well. If the format you want to use is common, PrettyTable makes this easy for you to do using the set_style method. If you want to produce an uncommon table, you'll have to do things slightly harder (see later).

Setting a table style

You can set the style for your table using the set_style method before any calls to print or get_string. Here's how to print a table in Markdown format:

from prettytable import MARKDOWN
table.set_style(MARKDOWN)
print(table)

In addition to MARKDOWN you can use these in-built styles:

  • DEFAULT - The default look, used to undo any style changes you may have made
  • PLAIN_COLUMNS - A borderless style that works well with command line programs for columnar data
  • MSWORD_FRIENDLY - A format which works nicely with Microsoft Word's "Convert to table" feature
  • ORGMODE - A table style that fits Org mode syntax
  • SINGLE_BORDER and DOUBLE_BORDER - Styles that use continuous single/double border lines with Box drawing characters for a fancier display on terminal

Other styles are likely to appear in future releases.

Changing the appearance of your table - the hard way

If you want to display your table in a style other than one of the in-built styles listed above, you'll have to set things up the hard way.

Don't worry, it's not really that hard!

Style options

PrettyTable has a number of style options which control various aspects of how tables are displayed. You have the freedom to set each of these options individually to whatever you prefer. The set_style method just does this automatically for you.

The options are:

Option Details
border A Boolean option (must be True or False). Controls whether a border is drawn inside and around the table.
preserve_internal_border A Boolean option (must be True or False). Controls whether borders are still drawn within the table even when border=False.
header A Boolean option (must be True or False). Controls whether the first row of the table is a header showing the names of all the fields.
hrules Controls printing of horizontal rules after rows. Allowed values: FRAME, HEADER, ALL, NONE.
HEADER, ALL, NONE These are variables defined inside the prettytable module so make sure you import them or use prettytable.FRAME etc.
vrules Controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE.
int_format A string which controls the way integer data is printed. This works like: print("%<int_format>d" % data).
float_format A string which controls the way floating point data is printed. This works like: print("%<float_format>f" % data).
custom_format A dictionary of field and callable. This allows you to set any format you want pf.custom_format["my_col_int"] = lambda f, v: f"{v:,}". The type of the callable is Callable[[str, Any], str]
padding_width Number of spaces on either side of column data (only used if left and right paddings are None).
left_padding_width Number of spaces on left-hand side of column data.
right_padding_width Number of spaces on right-hand side of column data.
vertical_char Single character string used to draw vertical lines. Default: |.
horizontal_char Single character string used to draw horizontal lines. Default: -.
_horizontal_align_char Single character string used to indicate column alignment in horizontal lines. Default: : for Markdown, otherwise None.
junction_char Single character string used to draw line junctions. Default: +.
top_junction_char Single character string used to draw top line junctions. Default: junction_char.
bottom_junction_char single character string used to draw bottom line junctions. Default: junction_char.
right_junction_char Single character string used to draw right line junctions. Default: junction_char.
left_junction_char Single character string used to draw left line junctions. Default: junction_char.
top_right_junction_char Single character string used to draw top-right line junctions. Default: junction_char.
top_left_junction_char Single character string used to draw top-left line junctions. Default: junction_char.
bottom_right_junction_char Single character string used to draw bottom-right line junctions. Default: junction_char.
bottom_left_junction_char Single character string used to draw bottom-left line junctions. Default: junction_char.

You can set the style options to your own settings in two ways:

Setting style options for the long term

If you want to print your table with a different style several times, you can set your option for the long term just by changing the appropriate attributes. If you never want your tables to have borders you can do this:

table.border = False
print(table)
print(table)
print(table)

Neither of the 3 tables printed by this will have borders, even if you do things like add extra rows in between them. The lack of borders will last until you do:

table.border = True

to turn them on again. This sort of long-term setting is exactly how set_style works. set_style just sets a bunch of attributes to pre-set values for you.

Note that if you know what style options you want at the moment you are creating your table, you can specify them using keyword arguments to the constructor. For example, the following two code blocks are equivalent:

table = PrettyTable()
table.border = False
table.header = False
table.padding_width = 5

table = PrettyTable(border=False, header=False, padding_width=5)

Changing style options just once

If you don't want to make long-term style changes by changing an attribute like in the previous section, you can make changes that last for just one get_string by giving those methods keyword arguments. To print two "normal" tables with one borderless table between them, you could do this:

print(table)
print(table.get_string(border=False))
print(table)

Changing the appearance of your table - with colors!

PrettyTable has the functionality of printing your table with ANSI color codes. This includes support for most Windows versions through Colorama. To get started, import the ColorTable class instead of PrettyTable.

-from prettytable import PrettyTable
+from prettytable.colortable import ColorTable

The ColorTable class can be used the same as PrettyTable, but it adds an extra property. You can now specify a custom theme that will format your table with colors.

from prettytable.colortable import ColorTable, Themes

table = ColorTable(theme=Themes.OCEAN)

print(table)

Creating a custom theme

The Theme class allows you to customize both the characters and colors used in your table.

Argument Description
default_color The color to use as default
vertical_char, horizontal_char, and junction_char The characters used for creating the outline of the table
vertical_color, horizontal_color, and junction_color The colors used to style each character.

Note: Colors are formatted with the Theme.format_code(s: str) function. It accepts a string. If the string starts with an escape code (like \x1b) then it will return the given string. If the string is just whitespace, it will return "". If the string is a number (like "34"), it will automatically format it into an escape code. I recommend you look into the source code for more information.

Displaying your table in JSON

PrettyTable will also print your tables in JSON, as a list of fields and an array of rows. Just like in ASCII form, you can actually get a string representation - just use get_json_string().

Displaying your table in HTML form

PrettyTable will also print your tables in HTML form, as <table>s. Just like in ASCII form, you can actually get a string representation - just use get_html_string(). HTML printing supports the fields, start, end, sortby and reversesort arguments in exactly the same way as ASCII printing.

Styling HTML tables

By default, PrettyTable outputs HTML for "vanilla" tables. The HTML code is quite simple. It looks like this:

<table>
  <thead>
    <tr>
      <th>City name</th>
      <th>Area</th>
      <th>Population</th>
      <th>Annual Rainfall</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Adelaide</td>
      <td>1295</td>
      <td>1158259</td>
      <td>600.5</td>
    </tr>
    <tr>
      <td>Brisbane</td>
      <td>5905</td>
      <td>1857594</td>
      <td>1146.4</td>
      ...
    </tr>
  </tbody>
</table>

If you like, you can ask PrettyTable to do its best to mimic the style options that your table has set using inline CSS. This is done by giving a format=True keyword argument to get_html_string method. Note that if you always want to print formatted HTML you can do:

table.format = True

and the setting will persist until you turn it off.

Just like with ASCII tables, if you want to change the table's style for just one get_html_string you can pass those methods' keyword arguments - exactly like print and get_string.

Setting HTML attributes

You can provide a dictionary of HTML attribute name/value pairs to the get_html_string method using the attributes keyword argument. This lets you specify common HTML attributes like id and class that can be used for linking to your tables or customising their appearance using CSS. For example:

print(table.get_html_string(attributes={"id":"my_table", "class":"red_table"}))

will print:

<table id="my_table" class="red_table">
  <thead>
    <tr>
      <th>City name</th>
      <th>Area</th>
      <th>Population</th>
      <th>Annual Rainfall</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      ... ... ...
    </tr>
  </tbody>
</table>

Miscellaneous things

Copying a table

You can call the copy method on a PrettyTable object without arguments to return an identical independent copy of the table.

If you want a copy of a PrettyTable object with just a subset of the rows, you can use list slicing notation:

new_table = old_table[0:5]

Contributing

After editing files, use the Black linter to auto-format changed lines.

python -m pip install black
black prettytable*.py

prettytable's People

Contributors

av-guy avatar bd103 avatar daibhid avatar davzucky avatar denballakh avatar dependabot[bot] avatar endolith avatar flaper87 avatar guysz avatar hugovk avatar jazzband-bot avatar jezdez avatar kinredon avatar ksunden avatar kzwolenik95 avatar lmaurits avatar markfickett avatar myheroyuki avatar narayanadithya avatar olafvdspek avatar phershbe avatar prasadkatti avatar pre-commit-ci[bot] avatar rdil avatar rickwporter avatar sarath191181208 avatar shobanchiddarth avatar stuertz avatar vrza avatar weakiwi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

prettytable's Issues

Convert to an image

Hello, I would like the ability to output a table to an image. Or would you have advice on how to do that?

ImportError: cannot import name 'MARKDOWN' from 'prettytable'

Hi,

I am getting error cannot import markdown on my Python3.8

>>> from prettytable import MARKDOWN
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'MARKDOWN' from 'prettytable' (/home/vkosuri/github/publish/venv/lib/python3.8/site-packages/prettytable.py)

Bug while creating HTML table with links.

from prettytable import PrettyTable


listsites1 = ["1", "2"]

table1 = PrettyTable()
table1.field_names = ['Links']
table1.add_rows(listsites1)
print(table1)


listsites2 = ["https://www.x.com", "https://www.x.com"]

table2 = PrettyTable()
table2.field_names = ['Links']
table2.add_rows(listsites2)
# solution  --> table2.add_rows(map(lambda x: [x], listsites2))
print(table2)

Output:

+-------+
| Links |
+-------+
|   1   |
|   2   |
+-------+
Traceback (most recent call last):
  File "c:\Users\AmericaN\Desktop\Lab\learn.py", line 16, in <module>
    table2.add_rows(listsites2)
  File "C:\Users\AmericaN\Desktop\Lab\MyEnv\lib\site-packages\prettytable\prettytable.py", line 1025, in add_rows
    self.add_row(row)
  File "C:\Users\AmericaN\Desktop\Lab\MyEnv\lib\site-packages\prettytable\prettytable.py", line 1037, in add_row
    raise Exception(
Exception: Row has incorrect number of values, (actual) 17!=1 (expected)

no name prettytable

conda list prettytable

packages in environment at /data/c03n02/cliu/software/anaconda2019/envs/skl:
Name Version Build Channel
prettytable 0.7.2 py_3 conda-forge

I have import it successuflly. But when restart this envrionment.
python -c "import prettytable" shows:
ModuleNotFoundError: No module named 'prettytable'

conda list prettytable is still in the print

python is 3.6.7 conda is 4.7.5

float_format with %

I can't find the way to show float values with % (0.0125 as 1,25% for example)

I tried:

table.float_format = '%0.2f' #(which should be the right way I suppose)
table.float_format = '%0.2'
table.float_format = '0.2%f'
table.float_format = '0.2%'

But every time there is an exception raised:
Exception: Invalid value for float_format! Must be a float format string.

What am I doing wrong or is it a bug?

column max width

Is there any way to limit the width of some columns in the table ?

Compatibility with PTable

Ideally a upcoming major version of PrettyTable should also be compatible with https://github.com/kxxoling/PTable/, a very prominent and adopted fork which also quickly slid into non-maintained status. The main problem is that it also uses installed name prettytable, but as a namespace prettytable/, and Python 3.7 (and probably earlier) will ignore prettytable.py when prettytable/ exists. And of course pip and setuptools will happy install both PrettyTable and PTable despite the clash.

There are not a lot of differences - most of the differences are patches which were submitted to PrettyTable but were not being merged at the time. It would be good to rectify this conflict.

Support joined cells

Would supporting joining table cells be something you might consider?

I want to make tables like the following:

+-------------+-----------+--------------+---------------+------------------------+------------+
|     byte    |     0     |       1      |       2       |            3           |  4 .. End  |
+-------------+-----------+--------------+---------------+----------+-------------+------------+
|     bit     |                                          |  15 .. 8 |    7 .. 0   |            |
+=============+===========+==============+===============+==========+=============+============+
| description | Report ID | Device Index | Feature Index | Function | Software ID | Parameters |
+-------------+-----------+--------------+---------------+----------+-------------+------------+

My use case is constructing packet structures, where a field might expand over several bytes or bits.

Add header_align argument

The idea here is to be able to align the header separately from the values. For example, when I print floats I like the decimal points to align, and I get that with align='r'. But then the header names are all the way to the right, and you end up with

                   x
    12346.657

whereas I'd like:
            x
    12346.657

Add ability to specify colgroup attributes for HTML table

The colgroup element has the ability to specify the widths of the individual columns for an HTML table. For inserting a table into confluence for example, it required colgroup to determine the width of columns.

Are you open to including the ability to specify colgroup attributes as an option to get_html_string

Happy to contribute a PR

Support markdown table alignment

If I use align='r' it aligns the text to the right in the markup itself:

|      |     3 |   101 |   201 |   301 |   401 |   501 |   601 |
|------|-------|-------|-------|-------|-------|-------|-------|
|  WP  | 5.556 | 8.690 | 8.732 | 8.746 | 8.753 | 8.757 | 8.760 |
|  Sim | 5.586 | 8.694 | 8.733 | 8.770 | 8.747 | 8.755 | 8.763 |
| Diff | 0.030 | 0.004 | 0.001 | 0.024 | 0.006 | 0.002 | 0.003 |

But this doesn't display aligned in markdown rendering:

3 101 201 301 401 501 601
WP 5.556 8.690 8.732 8.746 8.753 8.757 8.760
Sim 5.586 8.694 8.733 8.770 8.747 8.755 8.763
Diff 0.030 0.004 0.001 0.024 0.006 0.002 0.003

It should add markdown's alignment syntax:

|      |     3 |   101 |   201 |   301 |   401 |   501 |   601 |
|-----:|------:|------:|------:|------:|------:|------:|------:|
|  WP  | 5.556 | 8.690 | 8.732 | 8.746 | 8.753 | 8.757 | 8.760 |
|  Sim | 5.586 | 8.694 | 8.733 | 8.770 | 8.747 | 8.755 | 8.763 |
| Diff | 0.030 | 0.004 | 0.001 | 0.024 | 0.006 | 0.002 | 0.003 |

which renders like this:

3 101 201 301 401 501 601
WP 5.556 8.690 8.732 8.746 8.753 8.757 8.760
Sim 5.586 8.694 8.733 8.770 8.747 8.755 8.763
Diff 0.030 0.004 0.001 0.024 0.006 0.002 0.003

Add colorful tables support

Hi! Just as an idea, maybe you could add Colorama/Blessings/color code support for tables. Here's my idea.

from prettytable import PrettyTable, THEME
x = PrettyTable()
x.set_theme(THEME.OCEAN)
x.field_names = ["Name", "Age"]
x.add_row(["Jeff", 20])
x.add_row(["Joe", 19])
x.add_row(["Jim", 25])
x.add_row(["Liam", 10])

This would return something like this:
Colorful Table UWU

You could also have theme creation:

from colorama import FORE, init
init()

class THEME:
  OCEAN = {
    "default": FORE.LIGHTCYAN_EX,
    "border": FORE.BLUE,
    "decor": FORE.CYAN
  }

Some possible theme class creation variables:
default = everything else
border = main border
outline = border surrounding entire table, not inner lines
hborder = horizontal border
vborder = vertical border
decor = the "+" complimenting the tables
header = the header of the table

Note: this is the program i used to render the table.

y = '''
+------+-----+
| Name | Age |
+------+-----+
| Jeff |  20 |
| Joe  |  19 |
| Jim  |  25 |
| Liam |  10 |
+------+-----+
'''

blue = ["-", "|"]
cyan = ["+"]
lightcyan = ["0", "1", "2" "3", "4", "5", "6", "7", "8", "9", "2"]

z = ""

for i in y:
  if i == "\n":
    z += "\n"
  elif i in blue:
    z += "\033[34m" + i
  elif i in cyan:
    z += "\033[36m" + i
  elif i in lightcyan:
    z += "\033[96m" + i
  else:
    z += "\033[96m" + i

print(z)

I hope you enjoy this idea!

(I might fork this project later on and implement it myself!)

SyntaxWarning: "is" with a literal

len(val) is 0 should be replaced by len(val) == 0

kraken-app | /venv/lib/python3.8/site-packages/prettytable/prettytable.py:421: SyntaxWarning: "is" with a literal. Did you mean "=="?
kraken-app |   elif val is None or (isinstance(val, dict) and len(val) is 0):
kraken-app | /venv/lib/python3.8/site-packages/prettytable/prettytable.py:441: SyntaxWarning: "is" with a literal. Did you mean "=="?
kraken-app |   elif val is None or (isinstance(val, dict) and len(val) is 0):
kraken-app | /venv/lib/python3.8/site-packages/prettytable/prettytable.py:459: SyntaxWarning: "is" with a literal. Did you mean "=="?
kraken-app |   if val is None or (isinstance(val, dict) and len(val) is 0):
kraken-app | /venv/lib/python3.8/site-packages/prettytable/prettytable.py:476: SyntaxWarning: "is" with a literal. Did you mean "=="?
kraken-app |   if val is None or (isinstance(val, dict) and len(val) is 0):
kraken-app | /venv/lib/python3.8/site-packages/prettytable/prettytable.py:674: SyntaxWarning: "is" with a literal. Did you mean "=="?
kraken-app |   if val is None or (isinstance(val, dict) and len(val) is 0):
kraken-app | /venv/lib/python3.8/site-packages/prettytable/prettytable.py:691: SyntaxWarning: "is" with a literal. Did you mean "=="?
kraken-app |   if val is None or (isinstance(val, dict) and len(val) is 0):

Alignment broken for default case

I followed the README steps for doing column alignment:

from prettytable import PrettyTable


def main() -> None:
    x = PrettyTable()
    x.align = "r"
    x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
    x.add_rows(
        [
            ["Adelaide", 1295, 1158259, 600.5],
            ["Brisbane", 5905, 1857594, 1146.4],
            ["Darwin", 112, 120900, 1714.7],
            ["Hobart", 1357, 205556, 619.5],
            ["Sydney", 2058, 4336374, 1214.8],
            ["Melbourne", 1566, 3806092, 646.9],
            ["Perth", 5386, 1554769, 869.4],
        ]
    )
    print(x)


if __name__ == "__main__":
    main()

But the output is not aligned:

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
|  Adelaide | 1295 |  1158259   |      600.5      |
|  Brisbane | 5905 |  1857594   |      1146.4     |
|   Darwin  | 112  |   120900   |      1714.7     |
|   Hobart  | 1357 |   205556   |      619.5      |
|   Sydney  | 2058 |  4336374   |      1214.8     |
| Melbourne | 1566 |  3806092   |      646.9      |
|   Perth   | 5386 |  1554769   |      869.4      |
+-----------+------+------------+-----------------+

Am I missing something?

  • prettytable 2.1.0
  • Python 3.9.1

Too long name in row element

Some elements in the row have a broken column boundary because the name is too long.

Are there any suitable options for this problem?

Personally, if the name of the element is too long,

I would like to have an option to show only part of the name.

Test on Python 3.10

Add 3.10-dev to travis.yml and .github/workflow/test.yml, let's see if things already pass.

Also add to tox.ini. (Is it py310?)

Add custom format functions for field output to prettytable (For example to format date/datetime)

Hi,

Is it possible to have prettytable output datetime objects with a specific format in a field?

The default format is OK, but I would love it if I could customize the display format. Currently I am converting the datetime objects to strings before inserting them into the table. However, I think it would be better to insert them directly to make it easier to sort by date.

Then prettytable could format them however desired when requesting the table string.

V/R
Scot

Add option to make first column of table the header

The only option available currently is to make the first row of the table the header. I have a use case where I prefer the first column of the table to be a header, and then the second column be the data of my table.

Are you open to adding a flag to get_html_string which swaps the header to being vertical?

Happy to contribute a PR

Add ability to filter rows

Is there any way to filter rows? Like:

table.field_names = ['A', 'B', 'C']
table.get_string(filter = lambda row: row['C'] == 1)

Enable user to add a deep copy row

I hope prettytable would support user to add a deep copy row. The cells in table usually not a static value. It's fussy to just change one cell in the table (delete row first and insert a new row)

So I suggest to add a parameter for add_row:

def add_row(self, row, deepcopy=False):

    """Add a row to the table

    Arguments:

    row - row of data, should be a list with as many elements as the table
    has fields"""

    if self._field_names and len(row) != len(self._field_names):
        raise Exception("Row has incorrect number of values, (actual) %d!=%d (expected)" %(len(row),len(self._field_names)))
    if not self._field_names:
        self.field_names = [("Field %d" % (n+1)) for n in range(0,len(row))]
    self._rows.append(row if deepcopy else list(row))

I know this may run counter to prettytable's design philosophy, may be we can make _rows be a public variable.

Split/merge cells ?

Hi,

Thank you for this wonderful module. Is it possible to split or merge cells ? Can you give an example ?

Thanks

When running unitests with prettytable, got DeprecationWarning

I am using prettytable in my uint tests and I get the following warnings:

venv\lib\site-packages\prettytable-0.7.2-py3.7.egg\prettytable.py:74
venv\lib\site-packages\prettytable-0.7.2-py3.7.egg\prettytable.py:74
  C:\Users\saroa\repositories\eddington_core\venv\lib\site-packages\prettytable-0.7.2-py3.7.egg\prettytable.py:74: DeprecationWarning: invalid escape sequence \[

venv\lib\site-packages\prettytable-0.7.2-py3.7.egg\prettytable.py:800
venv\lib\site-packages\prettytable-0.7.2-py3.7.egg\prettytable.py:800
  C:\Users\saroa\repositories\eddington_core\venv\lib\site-packages\prettytable-0.7.2-py3.7.egg\prettytable.py:800: DeprecationWarning: invalid escape sequence \{

venv\lib\site-packages\prettytable-0.7.2-py3.7.egg\prettytable.py:801
venv\lib\site-packages\prettytable-0.7.2-py3.7.egg\prettytable.py:801
  C:\Users\saroa\repositories\eddington_core\venv\lib\site-packages\prettytable-0.7.2-py3.7.egg\prettytable.py:801: DeprecationWarning: invalid escape sequence \{

venv\lib\site-packages\prettytable-0.7.2-py3.7.egg\prettytable.py:802
venv\lib\site-packages\prettytable-0.7.2-py3.7.egg\prettytable.py:802
  C:\Users\saroa\repositories\eddington_core\venv\lib\site-packages\prettytable-0.7.2-py3.7.egg\prettytable.py:802: DeprecationWarning: invalid escape sequence \{

Maybe I can fix that.

Drop support for EOL Python 2.7 and 3.5

Python 2.7 is EOL since 2020-01-01.

Python 3.5 is EOL since 2020-09-30.

After prettytable 1.0 has been released (#18), support for Python 2.7 and 3.5 will be dropped, and released as prettytable 2.0.0.

Prettytable 1.x will be the last to support Python 2.7 and 3.5, and will remain available on PyPI.

The python_requires metadata will help those with modern pip (v9+) get the newest version of prettytable that supports their Python version.

don't output field row

I don't find any function to cancel output filed row, does the package support this ?

Clarify difference with other forks

It seems that there are a couple of forks of prettytable:

From #23, it seems that ptable and prettytable are not compatible if installed in the same environment. However, do they still have the same API? Are they any features in ptable/ptable2 not available in prettytable?

Now that prettytable is back alive and has a maintenance/distribution infrastructure in place, it would be good to keep the development in this repository and try to merge with the forks (ptable/ptable2)?!

Tabulators break formatting

I am trying to print a diff between different commits in Git. The string contains a tabulator character that seems to interfere with the centering.
Example string from diff:

diff --git program.c program.c
index 05ced0c..804cd7d 100644
--- partdiff.c
+++ partdiff.c
@@ -377,6 +377,7 @@ main (int argc, char** argv)
        struct calculation_arguments arguments;
        struct calculation_results results;

+       printf("Some random text!");
        askParams(&options, argc, argv);

        initVariables(&arguments, &results, &options);

Actually spelled out the "\t":

diff --git partdiff.c partdiff.c
index 05ced0c..804cd7d 100644
--- partdiff.c
+++ partdiff.c
@@ -377,6 +377,7 @@ main (int argc, char** argv)
 \tstruct calculation_arguments arguments;
 \tstruct calculation_results results;

+\tprintf("Some random text!");
 \taskParams(&options, argc, argv);

 \tinitVariables(&arguments, &results, &options);

Printing with a PrettyTable breaks the layout. If you replace the "\t" with any character it works fine,

|   4   | 2021-05-13 17:41:21.512372 | BUILD |    make   |       0       |       f0252dd       |         diff --git partdiff.c partdiff.c         |     |
|       |                            |       |           |               |                     |          index 05ced0c..804cd7d 100644           |     |
|       |                            |       |           |               |                     |                  --- partdiff.c                  |     |
|       |                            |       |           |               |                     |                  +++ partdiff.c                  |     |
|       |                            |       |           |               |                     | @@ -377,6 +377,7 @@ main (int argc, char** argv) |     |
|       |                            |       |           |               |                     |                                struct calculation_arguments arguments;                          |     |
|       |                            |       |           |               |                     |                                struct calculation_results results;                          |     |
|       |                            |       |           |               |                     |                                                  |     |
|       |                            |       |           |               |                     |                         +      printf("Some random text!");                          |     |
|       |                            |       |           |               |                     |                                askParams(&options, argc, argv);                          |     |
|       |                            |       |           |               |                     |                                                  |     |
|       |                            |       |           |               |                     |                                initVariables(&arguments, &results, &options);                          |     |
|       |                            |       |           |               |                     |                                                  |     |
+-------+----------------------------+-------+-----------+---------------+---------------------+--------------------------------------------------+-----+

Request: remove exclamation points from exceptions

This is an example of an exception I just got:

Exception: Invalid field name: f!

That's very confusing; I was trying to figure out how I passed the string 'f!'

Compare this to any Python exception:

3/0 
ZeroDivisionError: division by zero

No exclamation point. I'm not aware of any built in exception in Python that uses exclamation points.

If you must stick with using exclamation points or punctuation, please use quotes to make the field readable:

Exception: Invalid field name: 'f'!

Better display of Chinese

The display width of one Chinese character is not equal to the display width of two space characters. I recommend using chr (12288) as a filler for Chinese content.

print('[中文]')
print(f"[{chr(12288)}{chr(12288)}]")
print(f"[{' ' * 4}]")
[中文]
[  ]
[    ]

float_format kwargs doesn't work as intended

I found this documentation regarding a fixed issue, but I don't think the fix was carried over to add_columns:
https://code.google.com/archive/p/prettytable/issues/55

My issue is substantially the same as reported in that issue, but since that was seven years ago and I'm on Version 2.0.0, I'm guessing this should be resubmitted.

This code does not work:

from prettytable import PrettyTable
results = PrettyTable(float_format=".2")
results.add_column("Contract", pretty_names)
results.add_column("Positions", pretty_positions)
results.add_column("Shares", pretty_shares)
print(results)

The following, however, works fine:

from prettytable import PrettyTable
results = PrettyTable()
results.add_column("Contract", pretty_names)
results.add_column("Positions", pretty_positions)
results.add_column("Shares", pretty_shares)
results.float_format=".2"
print(results)

Cannot use PyInstaller to package application including PrettyTable

system: win10 2004
python: 3.8
prettytable: 2.0
pyinstaller: 4.0
pip: 19.2.3

this is my code

# test.py
from prettytable import PrettyTable
x = PrettyTable()
x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
x.add_row(["Adelaide", 1295, 1158259, 600.5])
x.add_row(["Brisbane", 5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

print(x.get_string())

input("input something:")

when I use pyinstaller -F test.py,l can not open the .exe file,has the following error

image

Add GitHub title + topics

Can only be done by a repo or orga owner I guess.

  • Set description to “Display tabular data in a visually appealing ASCII table format”
  • Add "#readme" to the website self-link, otherwise it's pretty useless.
  • Set topics like: python · package · python-3 · utility-library

Import docs from Google Code Archive

The README says:

This tutorial is distributed with PrettyTable and is meant to serve
as a "quick start" guide for the lazy or impatient. It is not an
exhaustive description of the whole API, and it is not guaranteed to be
100% up to date. For more complete and update documentation, check the
PrettyTable wiki.

The wiki is on the old Google Code Archive:

And links to two pages:

Let's move those to this repo as versioned MD or RST files.

There may be some overlap between the tutorial and the README, if so, perhaps they could be merged. Or create a new file for it.

Installation is short and out of date, it says to use easy_install, or to manually copy the file to certain directories for different operating systems (with python2.5 in the examples!). This could be replaced with modern pip install ... info near the top of the README.

What does `def _str_block_width(val)` return?

def _str_block_width(val):
    return sum(itermap(_char_block_width, itermap(ord, _re.sub("", val))))

I'm trying to understand the code and I can't find documentation for itermap(). What the heck is ord?

Implement Jazzband guidelines for prettytable

This issue tracks the implementation of the Jazzband guidelines for the project prettytable.

See the TODO list below for the generally required tasks, but feel free to update it in case the project requires it.

(Based on the list at jazzband/tablib#378.)

Feel free to ping a Jazzband roadie if you have any question.

TODOs

Merge with lmaurits/prettytable?

It looks like @lmaurits is the original author (i.e. same person as the Google Code archived repo owner).

It's unfortunate that, when this was exported from Google Code, GitHub isn't able to automatically trace this repo as a fork of https://github.com/lmaurits/prettytable. There are also many other "forks" that GitHub hasn't automatically traced.

Since you seem to have put the most effort among the forkers, maybe make @lmaurits aware of your fork and somehow arrange to merge back to the original, or take custody of the package on PyPI so you can publish updated versions?

CI: Test on Python 3.9 final

GitHub Actions and Travis CI now have Python 3.9 final.

Replace 3.9-dev with 3.9 in test.yml and .travis.yml.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.