list 左对齐输出
for line in [[1, 128, 1298039], [123388, 0, 2]]:
...: print('{:>8} {:>8} {:>8}'.format(*line))
...:
...:
1 128 1298039
123388 0 2
左右对齐
print(
...: f"{'Trades:':<15}{2034:>10}",
...: f"
{'Wins:':<15}{1232:>10}",
...: f"
{'Losses:':<15}{1035:>10}",
...: f"
{'Breakeven:':<15}{37:>10}",
...: f"
{'Win/Loss Ratio:':<15}{1.19:>10}",
...: f"
{'Mean Win:':<15}{0.381:>10}",
...: f"
{'Mean Loss:':<15}{-0.395:>10}",
...: f"
{'Mean:':<15}{0.026:>10}",
...: )
Trades: 2034
Wins: 1232
Losses: 1035
Breakeven: 37
Win/Loss Ratio: 1.19
Mean Win: 0.381
Mean Loss: -0.395
Mean: 0.026
In [11]:
Example 1 使用 "<" 左对齐
for line in [[1222222, "timestamp=1626749571096,values=80"], [123388, "timestamp=1626749571096,values=80"]]:
...: print('{:<20} {:<50}'.format(*line))
...:
1222222 timestamp=1626749571096,values=80
123388 timestamp=1626749571096,values=80
Example 2 : 使用 ">" 右对齐
for line in [[1222222, "timestamp=1626749571096,values=80"], [123388, "timestamp=1626749571096,values=80"]]:
...: ...: print('{:>20} {:<50}'.format(*line))
...:
1222222 timestamp=1626749571096,values=80
123388 timestamp=1626749571096,values=80
Example 3 : 使用 "^" 中间对其
for line in [[1222222, "timestamp=1626749571096,values=80000000333"], [123388, "timestamp=1626749571096,values=802"]]:
...: print('{:^20} {:^80}'.format(*line))
...:
1222222 timestamp=1626749571096,values=80000000333
123388 timestamp=1626749571096,values=802
Example 5 : 对其方式打印list
In [8]: names = ['Raj', 'Shivam', 'Shreeya', 'Kartik']
...: marks = [7, 9, 8, 5]
...: div = ['A', 'A', 'C', 'B']
...: id = [21, 52, 27, 38]
In [9]: for i in range(0, 4):
...: print(f"{names[i] : <10}{marks[i] : ^10}{div[i] : ^10}{id[i] : >5}")
...:
Raj 7 A 21
Shivam 9 A 52
Shreeya 8 C 27
Kartik 5 B 38
In [10]:
使用python-tabulate
python-tabulate 支持多种格式,详细请参考github
pip install tabulate
>>> from tabulate import tabulate
>>> table = [["Sun",696000,1989100000],["Earth",6371,5973.6],
... ["Moon",1737,73.5],["Mars",3390,641.85]]
>>> print(tabulate(table))
----- ------ -------------
Sun 696000 1.9891e+09
Earth 6371 5973.6
Moon 1737 73.5
Mars 3390 641.85
----- ------ -------------
参考:
https://stackoverflow.com/questions/8234445/format-output-string-right-alignment
https://github.com/astanin/python-tabulate
https://www.geeksforgeeks.org/string-alignment-in-python-f-string/