dan
dan

Reputation: 67

Python assign parameters dinamically to Format function

I have a simple script to format data. I don't know how many elements I have to format because they came in a variable array.

I think I need to pass parameters dynamically to the Format function. Are there some way to drive this case?

    def formatting(p_array):
        format_string = ''
        lin = ''
        for i in range(len(p_array)):
            format_string += '{:>20}'
            lin += "'"+p_array[i]+"'"
            if i < len(p_array)-1:
                lin += ","

        # Next line gives ERROR.
        print(format_string.format(lin))

    # c_attributes can have more o less elements.
    c_attributes = ['userAccountControl','cn', 'sAMAccountName', 'mail']
    formatting(c_attributes)

I receive the following error: "IndexError: tuple index out of range"

Upvotes: 0

Views: 55

Answers (1)

chepner
chepner

Reputation: 531055

You only need two lines of code:

format_string = '{:>20}'*len(p_array)
print(format_string.format(*p_array)

The first line builds up your format_string immediately, instead of looping over the elements of the input array. The second line correctly passes each element of that array to format_string.format as a separate argument, rather than passing a single string built from those elements.

You are trying to run "...".format("x,y,z") instead of "...".format(x, y, z).

Upvotes: 3

Related Questions