0

How can I use format() to print out a table like the one in the expected output? I tried and got an error:

unsupported format string passed to list.__format__
data = [[1, [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]], 
        [2, [1, 2, -999, 4, 5], [1, 2, 3.0, 4, 5]]]

print ("{:<10} {:<20} {:<20}".format('Test Case','Original','Clean-Up'))

for item in data:
    testcase, original, clean = item
    print ("{:<10} {:<50} {:<50}".format(testcase, original, clean))

Expected output:

    test case    original             clean-up
        1       1, 2, 3, 4, 5        1, 2, 3, 4, 5
        2       1, 2, -999, 4, 5     1, 2, 3.0, 4, 5
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    Use this for the inner lists: [How would you make a comma-separated string from a list of strings?](https://stackoverflow.com/questions/44778/how-would-you-make-a-comma-separated-string-from-a-list-of-strings) - your use of `format` seems to be correct otherwise. – mkrieger1 Aug 20 '21 at 08:05

2 Answers2

1

Try this:

for item in data:
    testcase, original, clean = item
    print ("{:<10} {:<20} {:<10}".format(testcase, ', '.join(str(i) for i in original), ', '.join(str(i) for i in clean)))

Output:

Test Case  Original             Clean-Up
1          1, 2, 3, 4, 5        1, 2, 3, 4, 5
2          1, 2, -999, 4, 5     1, 2, 3.0, 4, 5
1

Try with this code:

for item in data:
    testcase, original, clean = item
    print ("{:<10} {:<20} {:<10}".format(testcase, ', '.join(map(str, original)), ', '.join(map(str, clean))))

Output:

Test Case  Original             Clean-Up            
1          1, 2, 3, 4, 5        1, 2, 3, 4, 5
2          1, 2, -999, 4, 5     1, 2, 3.0, 4, 5

I used str.join and map to make the code work.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114