How to use Pretty Table in Python to print out dat

2019-04-09 06:21发布

问题:

I'm relatively new to Python Programming, using Python 3.x, and am working on a Barbershop P.O.S system where the admin will have the privilege to add Services and their corresponding Prices. I'm using the Pretty Table library to achieve printing out a table with serviceID, service and price.

Here's my code:

from prettytable import PrettyTable
import random

serviceID = []
services = []
price = []
x = PrettyTable()

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

while True:
try:

     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)

     print(x)


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

When I enter the first service and Price, the output is:

+-----------+---------+--------+
| ServiceID | Service | Price  |
+-----------+---------+--------+
|   [9880]  | ['box'] | ['90'] |
+-----------+---------+--------+

When I enter the 2nd service and price, the output is this:

+---------------+-----------------+--------------+
|   ServiceID   |     Service     |    Price     |
+---------------+-----------------+--------------+
| [9880, 47612] | ['box', 'trim'] | ['90', '80'] |
+---------------+-----------------+--------------+

I'd like the output to be this:

+---------------+-----------------+--------------+
|   ServiceID   |     Service     |    Price     |
+---------------+-----------------+--------------+
|  9880         |      box        |       90     |
|  47612        |     trim        |       80     |
+---------------+-----------------+--------------+

Does anyone know how to achieve this? Any help would be appreciated.

回答1:

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:

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 methonds 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