Reputation: 3218
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.
Upvotes: 0
Views: 113
Reputation: 1121584
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))
Upvotes: 1