Hristo Georgiev
Hristo Georgiev

Reputation: 69

How to format tuples?

I apologize if the title is misleading in any way. I am currently facing a problem with my program. My first function takes a string as input and turns it into a tuple. My second function is meant to modify and print the tuple in something like a table with fixed-width fields and that's where I get in trouble. Here is what I tried:

string = 'abc acb bac bca 100000'

def function_one(string):
    modify_one = string.split(' ')
    my_tuple = (modify_one[3], modify_one[2],
    modify_one[4], modify_one[1], modify_one[0])
    print(my_tuple)

    def function_two(my_tuple):

        print(my_tuple)
        formatted = u'{:<15} {:<15} {:<8} {:<5} {:<5}'.format(my_tuple[3], '|', my_tuple[2], '|', my_tuple[4], '|', my_tuple[1], '|', my_tuple[0])
        print(formatted)

    function_two(my_tuple)

function_one(string)

My output (only prints 3 out of 5):

('bca', 'bac', '100000', 'acb', 'abc')
('bca', 'bac', '100000', 'acb', 'abc')
acb             |               100000   |     abc

Important!
I know that just a single string can't look like a table. Originally I am asked to insert a text file in the program, something I haven't figured out how to do so far. I am using a single string just to make sure the functions are working properly.

Upvotes: 1

Views: 308

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140307

your format parameters contain the separators, but there aren't enough format specifiers in the format string.

you probably mean

'{:<15} | {:<15} | {:<8} | {:<5} | {:<5}'.format(my_tuple[3], my_tuple[2], my_tuple[4], my_tuple[1], my_tuple[0])

Which can also be written as follows to benefit from the fact that parameters can be unpacked positionally and format specifiers can specify the index of the parameter:

'{3:<15} | {2:<15} | {4:<8} | {1:<5} | {0:<5}'.format(*my_tuple)

Upvotes: 3

Related Questions