格式化输出字符串,右对齐-Python 实用宝典

格式化输出字符串,右对齐

我正在处理一个包含坐标x,y,z的文本文件 1 128 1298039 123388 0 2 .... 每行使用 words = line.split() 处理完数据后,我需要将坐标写回到另一个txt文件中,以使每一列中的项目(以及输入文件)都正确对齐。每行由坐标组成 line_new = words[0] + ' ' + words[1] + ' ' words[2]. std::setw()C ++中是否有任何类似操纵器的控件可以设置宽度和对齐方式?

问题:格式化输出字符串,右对齐

我正在处理一个包含坐标x,y,z的文本文件

     1      128  1298039
123388        0        2
....

每行使用

words = line.split()

处理完数据后,我需要将坐标写回到另一个txt文件中,以使每一列中的项目(以及输入文件)都正确对齐。每行由坐标组成

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

std::setw()C ++中是否有任何类似操纵器的控件可以设置宽度和对齐方式?

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?


回答 0

使用更新的str.format语法尝试这种方法:

line_new = '{:>12}  {:>12}  {:>12}'.format(word[0], word[1], word[2])

以下是使用旧%语法(对不支持的旧版本Python有用str.format)的方法:

line_new = '%12s  %12s  %12s' % (word[0], word[1], word[2])

Try this approach using the newer str.format syntax:

line_new = '{:>12}  {:>12}  {:>12}'.format(word[0], word[1], word[2])

And here's how to do it using the old % syntax (useful for older versions of Python that don't support str.format):

line_new = '%12s  %12s  %12s' % (word[0], word[1], word[2])

回答 1

可以使用rjust以下方法实现:

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

It can be achieved by using rjust:

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

回答 2

您可以像这样对齐它:

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

其中>表示“ 向右对齐 ”,8是特定值的宽度

这是一个证明:

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


       1      128  1298039
  123388        0        2

附言 *line表示该line列表将被解压缩,因此其.format(*line)工作方式类似于.format(line[0], line[1], line[2])(假设line一个仅包含三个元素的列表)。

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).


回答 3

我真的很喜欢Python 3.6+中的新文字字符串插值:

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

参考:PEP 498-文字字符串插值

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


回答 4

这是使用“ f-string”格式进行格式化的另一种方法:

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}",
)

这将提供以下输出:

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

您在这里的意思是第一列的长度为15个字符,并且左对齐,第二列的值(长度)为10个字符,并且右对齐。

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.


回答 5

输出的简单列表:

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

输出:

variable a    variable b
      0.33         66.67

%10.2f: 10是最小长度,2是小数位数。

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.


回答 6

要使用f字符串并控制尾随数字的数量,请执行以下操作:

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

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

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

本文由 Python 实用宝典 作者:Python实用宝典 发表,其版权均为 Python 实用宝典 所有,文章内容系作者个人观点,不代表 Python 实用宝典 对观点赞同或支持。如需转载,请注明文章来源。
3

抱歉,评论已关闭!