0

I am playing a little with PrettyTable in Python and I noticed completely different behavior in Python2 and Python 3. Can somebody exactly explain me the difference in output? Nothing in docs gave me satisfied answer for that. But let's start with little code. Let's start with creating my_table

from prettytable import PrettyTable
my_table = PrettyTable()
my_table.field_name = ['A','B']

It creates two column table with column A and column B. Let's add on row to it, but assume that value in cell can have multi lines, separated by Python new line '\n' , as the example some properties of parameter from column A.

row = ['parameter1', 'component: my_component\nname:somename\nmode: magic\ndate: None']
my_table.add_row(row)

Generally the information in row can be anything, it's just a string retrieved from other function. As you can see, it has '\n' inside. The thing that I don't completely understand is the output of print function.

I have in Python2

print(my_table.get_string().encode('utf-8'))

Which have me output like this:

+------------+-------------------------+
|  Field 1   |         Field 2         |
+------------+-------------------------+
| parameter1 | component: my_component |
|            |      name:somename      |
|            |       mode: magic       |
|            |        date: None       |
+------------+-------------------------+

But in Python3 I have:

+------------+-------------------------+ | Field 1 | Field 2 | +------------+-------------------------+ | parameter1 | component: my_component | | | name:somename | | | mode: magic | | | date: None | +------------+-------------------------+

If I completely removes the encode part, it seems that output looks ok on both version of Python.

So when I have

print(my_table.get_string())

It works on Python3 and Python2. Should I remove the encode part from code? It is save to assume it is not necessary? Where is the problem exactly?

Tatarinho
  • 754
  • 2
  • 11
  • 31
  • 1
    Generally, it isn't useful to encode a string before passing it to `print()` in Python 3, because the resulting byte string is formatted using `repr`, ie. including quotes and escape sequences. This is different for Python 2, where `print` simply forwards byte strings literally. – lenz Mar 20 '19 at 14:42
  • If your terminal is set up properly, you don't need to `.encode()` Unicode strings when printing in Python 2 either. – Mark Tolonen Mar 20 '19 at 20:51
  • @MarkTolonen what if not? How can I handle both versions in one way? – Tatarinho Mar 21 '19 at 07:25
  • Ok I will use 'six' library to handle both cases. Thanks for comments – Tatarinho Mar 21 '19 at 12:27

0 Answers0