How to format the writing of python output in ordered column-wise?

Viewed 21

I am looking for a way to write the text mentioned below,

Step:   0       ID: [291, 339, 377, 441]     Std: 0.1379
Step:   0       ID: [166, 207, 365, 424]     Std: 0.2927
Step:   0       ID: [401, 418, 443]      Std: 0.0997
Step:   0       ID: [160, 170, 222, 394]     Std: 0.2062
Step:   0       ID: [163, 175, 261]      Std: 0.0303

in a format similar to

Step:   0       ID: [291, 339, 377, 441]     Std: 0.1379
Step:   0       ID: [166, 207, 365, 424]     Std: 0.2927
Step:   0       ID: [401, 418, 443]          Std: 0.0997
Step:   0       ID: [160, 170, 222, 394]     Std: 0.2062
Step:   0       ID: [163, 175, 261]          Std: 0.0303

using command alike

file.write(f' Step: {step}   ID: {ids}  Std: {stds}').

Is there any way to achieve so?

1 Answers

You didn't specify the variables you used so I'm going to assume that ids is a list. Python includes a string formatting mini language with which you can align values to a fixed width. This doesn't work with lists directly so you have to convert the list to a string first:

file.write(f' Step: {step}   ID: {str(ids):25}  Std: {stds}').

The above ensures that the output of str(ids) is 25 characters long.

Related