jus*_*tik 133 python alignment string-formatting
我正在处理包含坐标x,y,z的文本文件
1 128 1298039
123388 0 2
....
Run Code Online (Sandbox Code Playgroud)
每行使用分为3个项目
words = line.split()
Run Code Online (Sandbox Code Playgroud)
在处理数据之后,我需要在另一个txt文件中写回坐标,以便每列中的项目对齐(以及输入文件).每一行都由坐标组成
line_new = words[0] + ' ' + words[1] + ' ' words[2].
Run Code Online (Sandbox Code Playgroud)
std::setw()在C++中是否有类似的操纵器允许设置宽度和对齐?
Mar*_*ers 207
使用较新的str.format语法尝试此方法:
line_new = '{:>12} {:>12} {:>12}'.format(word[0], word[1], word[2])
Run Code Online (Sandbox Code Playgroud)
这里是如何使用旧做%语法(旧版本不支持的Python有用的str.format):
line_new = '%12s %12s %12s' % (word[0], word[1], word[2])
Run Code Online (Sandbox Code Playgroud)
clw*_*wen 47
它可以通过使用rjust:
line_new = word[0].rjust(10) + word[1].rjust(10) + word[2].rjust(10)
Run Code Online (Sandbox Code Playgroud)
Tad*_*eck 46
您可以这样对齐:
print('{:>8} {:>8} {:>8}'.format(*words))
Run Code Online (Sandbox Code Playgroud)
其中的>意思是" 对齐到右边 ",8是特定值的宽度.
这是一个证明:
>>> for line in [[1, 128, 1298039], [123388, 0, 2]]:
print('{:>8} {:>8} {:>8}'.format(*line))
1 128 1298039
123388 0 2
Run Code Online (Sandbox Code Playgroud)
PS.*line意味着line列表将被解压缩,所以.format(*line)工作方式类似于.format(line[0], line[1], line[2])(假设line是仅具有三个元素的列表).
dmi*_*nov 21
我非常喜欢Python 3.6+中新的字符串插值:
line_new = f'{word[0]:>12} {word[1]:>12} {word[2]:>12}'
Run Code Online (Sandbox Code Playgroud)
这是使用“ 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}",
)
Run Code Online (Sandbox Code Playgroud)
这将提供以下输出:
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
Run Code Online (Sandbox Code Playgroud)
您在这里的意思是第一列的长度为15个字符,并且左对齐,第二列的值(长度)为10个字符,并且右对齐。
要通过使用 f 字符串并控制尾随数字的数量来做到这一点:
print(f'A number -> {my_number:>20.5f}')
Run Code Online (Sandbox Code Playgroud)
输出的简单列表:
a = 0.3333333
b = 200/3
print("variable a variable b")
print("%10.2f %10.2f" % (a, b))
Run Code Online (Sandbox Code Playgroud)
输出:
variable a variable b
0.33 66.67
Run Code Online (Sandbox Code Playgroud)
%10.2f: 10是最小长度,2是小数位数。
| 归档时间: |
|
| 查看次数: |
222866 次 |
| 最近记录: |