0

I am trying to format an array using the prettytable library. Here is my code:

from prettytable import PrettyTable
arrayHR = [1,2,3,4,5,6,7,8,9,10]
print ("arrayHR:", arrayHR)
x = PrettyTable(["Heart Rate"])
for row in arrayHR:
    x.add_row(row)

This results in the following error:

arrayHR: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    Traceback (most recent call last):
      File "C:\Users\aag\Documents\Python\test.py", line 7, in <module>
    x.add_row(row)
      File "C:\Python33\lib\site-packages\prettytable.py", line 817, in add_row
    if self._field_names and len(row) != len(self._field_names):
TypeError: object of type 'int' has no len()

What am I doing wrong?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
aag
  • 680
  • 2
  • 12
  • 33
  • Thanks Sundar. Your suggestion works. However, prettytable will format each value of the array as a field in its own column. This may be desirable in certain cases. Jonrsharpe's method results in a vertical column, which in my case is the preferred behavior. – aag May 29 '14 at 12:47

1 Answers1

4

According to the documentation, add_row is expecting a list, not an int, as an argument. Assuming that you want the values in arrayHR to be the first value in each row, you could do:

x = PrettyTable(["Heart Rate"])
for row in arrayHR:
    x.add_row([row])

or adopt the add_column example, also from the documentation:

x = PrettyTable()
x.add_column("Heart Rate", arrayHR)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437