简体   繁体   English

如何使用 Python 字符串格式(右对齐)消除空格?

[英]How to eliminate white space with Python string formatting (right justified)?

When using this code:使用此代码时:

units = ['Temp [C]', 'v [m3/kg]', 'u [kJ/kg]', 's [kJ/kgK]', '[  new   ]']
data = ([1, 2, 1, 3,5], [0, 1, 0, 3, 5])

fmt_string = '{:>15}' * len(units)
print(fmt_string.format(*units))
for row in data:
    print(fmt_string.format(*row))

How can I eliminate the white spaces in front of the output so that it DOES NOT look like this:如何消除输出前面的空格,使其看起来不像这样:

错误的输出

And it WOULD look like this:它看起来像这样:

正确的输出

Ultimately I need the output (with more complex input) to look like this:最终我需要输出(具有更复杂的输入)看起来像这样:

Temp [C]  v [m3/kg]  u [kJ/kg]  h [kJ/kg]  s [kJ/kgK]
     0.0  0.0009977       0.04       5.03      0.0001
    20.0  0.0009996      83.61      88.61      0.2954
    40.0  0.0010057     166.92     171.95      0.5705
    60.0  0.0010149     250.29     255.36      0.8287
    80.0  0.0010267     333.82     338.96      1.0723
   100.0  0.0010410     417.65     422.85      1.3034
   120.0  0.0010576     501.91     507.19      1.5236
   140.0  0.0010769     586.80     592.18      1.7344
   160.0  0.0010988     672.55     678.04      1.9374
   180.0  0.0011240     759.47     765.09      2.1338
   200.0  0.0011531     847.92     853.68      2.3251
   220.0  0.0011868     938.39     944.32      2.5127
   240.0  0.0012268    1031.60    1037.70      2.6983
   260.0  0.0012755    1128.50    1134.90      2.8841

You can use units = [re.sub('\\s+', '', u) for u in units] to remove the whitespace of a string within a list, especially if the whitespace is within square brackets:您可以使用units = [re.sub('\\s+', '', u) for u in units]删除列表中字符串的空格,尤其是当空格在方括号内时:

Your code:您的代码:

units = ['Temp [C]', 'v [m3/kg]', 'u [kJ/kg]', 's [kJ/kgK]', '[  new   ]']
data = ([1, 2, 1, 3,5], [0, 1, 0, 3, 5])

fmt_string = '{:>15}' * len(units)
print(fmt_string.format(*units))
for row in data:
    print(fmt_string.format(*row))

Out[1]:
Temp [C]      v [m3/kg]      u [kJ/kg]     s [kJ/kgK]     [  new   ]
       1              2              1              3              5
       0              1              0              3              5

New Code (Notice the new output of "[new]" column):新代码(注意“[new]”列的新输出):

units = [re.sub('\s+', '', u) for u in units]
fmt_string = '{:>15}' * len(units)
print(fmt_string.format(*units))
for row in data:
    print(fmt_string.format(*row))

Out[2]:
 Temp[C]       v[m3/kg]       u[kJ/kg]      s[kJ/kgK]          [new]
       1              2              1              3              5
       0              1              0              3              5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM