We can do by adding row into PrettyTable object by add_row method.

Demo:

>>> from prettytable import PrettyTable
>>> import random
>>> 
>>> x = PrettyTable(["ServiceID", "Service", "Price"])
>>> 
>>> while True:
...     #- Get value
...     ID = random.randint(1,90000) #range high to lower probability of non-uniqueness
...     prompt1 = raw_input("Please add a service name to the list\n")
...     try:
...         #- Type Casting.
...         prompt2 = int(raw_input("Please enter a price for the service\n"))
...     except ValueError:
...         print("Please enter valid type")
...         continue
...     #- Add row
...     x.add_row([ID, prompt1, prompt2])
...     #- Ask user to Continue or not.
...     choice = raw_input("Continue yes/ no:").lower()
...     if not(choice=="yes" or choice=="y"):
...         break
... 
Please add a service name to the list
2
Please enter a price for the service
3
Continue yes/ no:y
Please add a service name to the list
4
Please enter a price for the service
6
Continue yes/ no:y
Please add a service name to the list
5
Please enter a price for the service
7
Continue yes/ no:n
>>> print x
+-----------+---------+-------+
| ServiceID | Service | Price |
+-----------+---------+-------+
|   38515   |    2    |   3   |
|    8680   |    4    |   6   |
|   51188   |    5    |   7   |
+-----------+---------+-------+
>>> 

Delete Row:

Use del_row() method. We need to pass index of row which we want to remove.

>>> print x
+-----------+---------+-------+
| ServiceID | Service | Price |
+-----------+---------+-------+
|   38515   |    2    |   3   |
|    8680   |    4    |   6   |
|   51188   |    5    |   7   |
+-----------+---------+-------+
>>> x.del_row(1)
>>> print x
+-----------+---------+-------+
| ServiceID | Service | Price |
+-----------+---------+-------+
|   38515   |    2    |   3   |
|   51188   |    5    |   7   |
+-----------+---------+-------+

Need to handle exception if we provide index value greater then total rows in exception will raise, that need to handle in ur code.

Exception is:

>>> x.del_row(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/prettytable.py", line 832, in del_row
    raise Exception("Cant delete row at index %d, table only has %d rows!" % (row_index, len(self._rows)))
Exception: Cant delete row at index 10, table only has 2 rows!

Note:

  1. Use raw_input() for Python 2.x

  2. Use input() for Python 3.x

Answer from Vivek Sable on Stack Overflow
🌐
PyPI
pypi.org › project › prettytable
prettytable · PyPI
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)
      » pip install prettytable
    
Published   Nov 14, 2025
Version   3.17.0
🌐
ZetCode
zetcode.com › python › prettytable
Python PrettyTable - generating tables in Python with PrettyTable
January 29, 2024 - The example reads data from the data.html file and generates a PrettyTable with the from_html_one method. With the sortby property, we specify which column is going to be sorted. The reversesort property controls the direction of sorting (ascending vs descending).
🌐
GeeksforGeeks
geeksforgeeks.org › python › creating-tables-with-prettytable-library-python
Creating Tables with PrettyTable Library - Python - GeeksforGeeks
August 18, 2020 - ... from prettytable import PrettyTable # Specify the Column Names while initializing the Table myTable = PrettyTable(["Student Name", "Class", "Section", "Percentage"]) # Add rows myTable.add_row(["Leanord", "X", "B", "91.2 %"]) myTable.ad...
🌐
ProgramCreek
programcreek.com › python › example › 58616 › prettytable.PrettyTable
Python Examples of prettytable.PrettyTable
def show_table(request_flag, file_list_tmp): rows = ["序列号", "文件/目录名", "文件大小"] if WIN_PLATFORM: encoding = 'gbk' else: encoding = 'utf-8' table = PrettyTable(rows, encoding=encoding) if not request_flag: print(file_list_tmp) return global file_list file_list = file_list_tmp table.padding_width = 1 for i, val in enumerate(file_list): table.add_row([i, val['name'], get_size_in_nice_string(val['size'])]) print(table)
🌐
PyPI
pypi.org › project › prettyTables
prettyTables · PyPI
This is a python package that aims to provide a simple and pretty way of printing tables to the console making use of a class.
      » pip install prettyTables
    
Published   Jul 11, 2022
Version   1.1.5
🌐
Readthedocs
ptable.readthedocs.io › en › latest › tutorial.html
Tutorial — PTable 0.9.0 documentation
PrettyTable will also print your tables in HTML form, as <table>s. Just like in ASCII form, you can actually print your table - just use print_html() - or get a string representation - just use get_html_string().
🌐
Google Code
code.google.com › archive › p › prettytable › wikis › Tutorial.wiki
Google Code Archive - Long-term storage for Google Code Project Hosting.
Archive · Skip to content · The Google Code Archive requires JavaScript to be enabled in your browser · Google · About Google · Privacy · Terms
🌐
GitHub
github.com › lmaurits › prettytable
GitHub - lmaurits/prettytable: Automatically exported from code.google.com/p/prettytable · GitHub
For example, the following two code blocks are equivalent: x = PrettyTable() x.border = False x.header = False x.padding_width = 5 x = PrettyTable(border=False, header=False, padding_width=5) == Changing style options just once == If you don't ...
Starred by 31 users
Forked by 6 users
Languages   Python
Find elsewhere
Top answer
1 of 2
4

We can do by adding row into PrettyTable object by add_row method.

Demo:

>>> from prettytable import PrettyTable
>>> import random
>>> 
>>> x = PrettyTable(["ServiceID", "Service", "Price"])
>>> 
>>> while True:
...     #- Get value
...     ID = random.randint(1,90000) #range high to lower probability of non-uniqueness
...     prompt1 = raw_input("Please add a service name to the list\n")
...     try:
...         #- Type Casting.
...         prompt2 = int(raw_input("Please enter a price for the service\n"))
...     except ValueError:
...         print("Please enter valid type")
...         continue
...     #- Add row
...     x.add_row([ID, prompt1, prompt2])
...     #- Ask user to Continue or not.
...     choice = raw_input("Continue yes/ no:").lower()
...     if not(choice=="yes" or choice=="y"):
...         break
... 
Please add a service name to the list
2
Please enter a price for the service
3
Continue yes/ no:y
Please add a service name to the list
4
Please enter a price for the service
6
Continue yes/ no:y
Please add a service name to the list
5
Please enter a price for the service
7
Continue yes/ no:n
>>> print x
+-----------+---------+-------+
| ServiceID | Service | Price |
+-----------+---------+-------+
|   38515   |    2    |   3   |
|    8680   |    4    |   6   |
|   51188   |    5    |   7   |
+-----------+---------+-------+
>>> 

Delete Row:

Use del_row() method. We need to pass index of row which we want to remove.

>>> print x
+-----------+---------+-------+
| ServiceID | Service | Price |
+-----------+---------+-------+
|   38515   |    2    |   3   |
|    8680   |    4    |   6   |
|   51188   |    5    |   7   |
+-----------+---------+-------+
>>> x.del_row(1)
>>> print x
+-----------+---------+-------+
| ServiceID | Service | Price |
+-----------+---------+-------+
|   38515   |    2    |   3   |
|   51188   |    5    |   7   |
+-----------+---------+-------+

Need to handle exception if we provide index value greater then total rows in exception will raise, that need to handle in ur code.

Exception is:

>>> x.del_row(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/prettytable.py", line 832, in del_row
    raise Exception("Cant delete row at index %d, table only has %d rows!" % (row_index, len(self._rows)))
Exception: Cant delete row at index 10, table only has 2 rows!

Note:

  1. Use raw_input() for Python 2.x

  2. Use input() for Python 3.x

2 of 2
0

I've accomplished that by always creating a new instance of the class prettytable.PrettyTable inside the while loop.

from prettytable import PrettyTable
import random

serviceID = []
services = []
price = []

while True:
    try:
        x = PrettyTable()

        ID = random.randint(1,90000) #range high to lower probability of non-uniqueness
        serviceID.append(ID) #Generates unique ID for each service

        prompt1 = input("Please add a service name to the list\n")
        services.append(prompt1)

        prompt2 = input("Please enter a price for the service\n")
        prompt2 == int(prompt2)
        price.append(prompt2)

        x.add_column("ServiceID", serviceID)
        x.add_column("Service", services)
        x.add_column("Price", price)

        print(x)


    except ValueError:
        print("Please enter valid type")
        continue

Here is my version of code using methods field_names() and add_row().

from prettytable import PrettyTable
import random

serviceID = []
services = []
price = []

x = PrettyTable()

x.field_names = ["ServiceID", "Service", "Price"]

while True:
    try:
         ID = random.randint(1,90000) #range high to lower probability of non-uniqueness
         serviceID.append(ID) # in order to store new value if you will need it later

         prompt1 = input("Please add a service name to the list\n")
         services.append(prompt1) # in order to store new value if you will need it later

         prompt2 = input("Please enter a price for the service\n")
         prompt2 == int(prompt2)
         services.append(prompt2) # in order to store new value if you will need it later

         x.add_row([ID, prompt1, prompt2])
         print(x)

    except ValueError:
        print("Please enter valid type")
        continue
🌐
Javatpoint
javatpoint.com › prettytable-in-python
Prettytable in Python - Javatpoint
Prettytable in Python with python, tutorial, tkinter, button, overview, entry, checkbutton, canvas, frame, environment set-up, first python program, operators, etc.
🌐
Medium
medium.com › @michaelperssonse › python-tutorial-prettytable-2e505be61630
Python Tutorial: PrettyTable. How to print simple and beautiful… | by Michael Persson | Medium
September 24, 2023 - Python Tutorial: PrettyTable How to print simple and beautiful tables in Python In my line of work as a software test engineer, I sometimes write small python scripts that fetch data from test …
🌐
CloudDefense.ai
clouddefense.ai › code › python › example › prettytable
Top 10 Examples of <!-- -->prettytable<!-- --> code in Python | CloudDefense.AI
Pretty-print a contingency table Parameters ---------- ct : the contingency table Returns ------- pretty_table : a fancier string representation of the table """ output = StringIO() rich_ct(ct).to_csv(output) output.seek(0) pretty_table = prettytable.from_csv(output) pretty_table.padding_width = 0 pretty_table.align = 'r' pretty_table.align[pretty_table.field_names[0]] = 'l' return pretty_table
🌐
Snyk
snyk.io › advisor › prettytable › functions › prettytable.prettytable
How to use the prettytable.PrettyTable function in prettytable | Snyk
def print_issues(data): n = ["id","priority","status","title"] n = [ i.upper() for i in n ] table = prettytable.PrettyTable(n) for issue in data["issues"]: table.add_row([issue["id"],issue["priority"]["name"],issue["status"]["name"], issue["subject"]]) print(table) A simple Python library for easily displaying tabular data in a visually appealing ASCII table format
🌐
Stack Overflow
stackoverflow.com › questions › 71332565 › prettytable-python-table-structure
PrettyTable Python table structure - Stack Overflow
I wanted to construct a table in the Below format using python. Edit : Sorry for not writing the question properly I have used PrettyTable t = PrettyTable() t.field_names =["TestCase Name",&
🌐
Stack Overflow
stackoverflow.com › questions › 70254382 › how-to-make-a-table-in-python-using-prettytable-packet
How to make a Table in Python using PrettyTable Packet - Stack Overflow
from prettytable import PrettyTable columns = ["Student Name", "Class", "Contact Number", "Job"] myTable = PrettyTable() # Add Columns myTable.add_column(columns[0], ["Student Name", "Trincomalee", "Michael", "Nick", "Gibbs"] myTable.add_co...
🌐
Abilian
lab.abilian.com › Tech › Python › Useful Libraries › (Pretty) tables in Python
(Pretty) tables in Python - Abilian Innovation Lab
To use the PrettyTable library in Python, you first need to install it using pip: ... Then, you can create a new instance of the PrettyTable class and add data to it using the add_row() method. For example:
🌐
GitHub
github.com › prettytable › prettytable › releases
Releases · prettytable/prettytable
Add demo to __main__: python -m prettytable (#347) @hugovk · Update Ruff: more f-strings and sort __all__ (#348) @hugovk · Fix default styles not being reset between set_style() calls (#344) @MonstersInc-sudo · Fix add_autoindex alignment for HTML (#345) @stuertz ·
Author   prettytable
🌐
GitHub
github.com › kxxoling › PTable
GitHub - kxxoling/PTable: PrettyTable is a simple Python library designed to make it quick and easy to represent tabular data in visually appealing ASCII tables. · GitHub
PrettyTable is a simple Python library designed to make it quick and easy to represent tabular data in visually appealing ASCII tables. - kxxoling/PTable
Starred by 127 users
Forked by 47 users
Languages   Python 99.0% | Makefile 1.0%
🌐
Medium
kumudithaudaya.medium.com › display-a-table-in-a-database-in-html-using-prettytable-python-70d7325f2e46
Display a table in a database in HTML using prettytable python | by Kumuditha Karunarathna | Medium
May 6, 2021 - Hi everyone this is my 3rd blog post, on this blog post I’m going to show you how to display a table in a database in an HTML file using python prettytable.