[python] Format output string, right alignment

I am processing a text file containing coordinates x, y, z

     1      128  1298039
123388        0        2
....

every line is delimited into 3 items using

words = line.split()

After processing data I need to write coordinates back in another txt file so as items in each column are aligned right (as well as the input file). Every line is composed of the coordinates

line_new = words[0]  + '  ' + words[1]  + '  ' words[2].

Is there any manipulator like std::setw() etc. in C++ allowing to set the width and alignment?

This question is related to python alignment string-formatting

The answer is


Simple tabulation of the output:

a = 0.3333333
b = 200/3
print("variable a    variable b")
print("%10.2f    %10.2f" % (a, b))

output:

variable a    variable b
      0.33         66.67

%10.2f: 10 is the minimum length and 2 is the number of decimal places.


You can align it like that:

print('{:>8} {:>8} {:>8}'.format(*words))

where > means "align to right" and 8 is the width for specific value.

And here is a proof:

>>> for line in [[1, 128, 1298039], [123388, 0, 2]]:
    print('{:>8} {:>8} {:>8}'.format(*line))


       1      128  1298039
  123388        0        2

Ps. *line means the line list will be unpacked, so .format(*line) works similarly to .format(line[0], line[1], line[2]) (assuming line is a list with only three elements).


I really enjoy a new literal string interpolation in Python 3.6+:

line_new = f'{word[0]:>12}  {word[1]:>12}  {word[2]:>12}'

Reference: PEP 498 -- Literal String Interpolation


Here is another way how you can format using 'f-string' format:

print(
    f"{'Trades:':<15}{cnt:>10}",
    f"\n{'Wins:':<15}{wins:>10}",
    f"\n{'Losses:':<15}{losses:>10}",
    f"\n{'Breakeven:':<15}{evens:>10}",
    f"\n{'Win/Loss Ratio:':<15}{win_r:>10}",
    f"\n{'Mean Win:':<15}{mean_w:>10}",
    f"\n{'Mean Loss:':<15}{mean_l:>10}",
    f"\n{'Mean:':<15}{mean_trd:>10}",
    f"\n{'Std Dev:':<15}{sd:>10}",
    f"\n{'Max Loss:':<15}{max_l:>10}",
    f"\n{'Max Win:':<15}{max_w:>10}",
    f"\n{'Sharpe Ratio:':<15}{sharpe_r:>10}",
)

This will provide the following output:

Trades:              2304
Wins:                1232
Losses:              1035
Breakeven:             37
Win/Loss Ratio:      1.19
Mean Win:           0.381
Mean Loss:         -0.395
Mean:               0.026
Std Dev:             0.56
Max Loss:          -3.406
Max Win:             4.09
Sharpe Ratio:      0.7395

What you are doing here is you are saying that the first column is 15 chars long and it's left justified and second column (values) is 10 chars long and it's right justified.


It can be achieved by using rjust:

line_new = word[0].rjust(10) + word[1].rjust(10) + word[2].rjust(10)

To do it by using f-string and with control of the number of trailing digits:

print(f'A number -> {my_number:>20.5f}')

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to alignment

How do I center text vertically and horizontally in Flutter? CSS align one item right with flexbox What's the difference between align-content and align-items? align images side by side in html How to align iframe always in the center How to make popup look at the centre of the screen? Responsive image align center bootstrap 3 How to align title at center of ActionBar in default theme(Theme.Holo.Light) Center align a column in twitter bootstrap How do I position an image at the bottom of div?

Examples related to string-formatting

JavaScript Chart.js - Custom data formatting to display on tooltip Format in kotlin string templates Converting Float to Dollars and Cents Chart.js - Formatting Y axis String.Format not work in TypeScript Use StringFormat to add a string to a WPF XAML binding How to format number of decimal places in wpf using style/template? How to left align a fixed width string? Convert Java Date to UTC String Format a Go string without printing?