0

I am trying to print a tuple in a file as:

for row in s:
    # Loop over columns.
    for column in row:
        print(column, type(column), end=" ")
        of1.write("%s  " % column)
        #of1.write("{:<10}{:<8}{:<23}{:<20}\n".format(row))
        of1.write("\n")
        print(end="\n")

all the elements are str as from the output of print statement:

64.08K <class 'str'> 20.0 <class 'str'> 0.95 <class 'str'> 1.7796943385724604e-05 <class 'str'> 

The code works fine, but as obvious, not well formatted. I am trying to use format statement for better formatting as in the commented line, but it is giving error:

File "eos_res.py", line 54, in <module>
    of1.write("{:<10}{:<8}{:<23}{:<20}\n".format(row))
IndexError: tuple index out of range

Kindly help.

0

1 Answer 1

1

You are trying to pass the whole row as one value to format. Use:

of1.write("{:<10}{:<8}{:<23}{:<20}\n".format(*row))

to have Python pass the individual values of row to .format().

Alternatively, use a format that pulls out individual indexes from the one positional argument:

of1.write("{0[0]:<10}{0[1]:<8}{0[2]:<23}{0[3]:<20}\n".format(row))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.