[英]Formatting float in python also before the decimal separator
I am formatting floats as follows:我正在格式化浮点数,如下所示:
logFile.write("Loadcase: %6i %2i %4i %2.2f %2.2f %4f + %4f -> " %(i, freq, amp, cutoff, end_time, penalty_inc, stab_inc))
and the result is like:结果是这样的:
Loadcase: 5001 1 50 19.00 20.00 0.000000 + 0.000000 -> 0.495386 (ok)
Loadcase: 5002 2 50 9.50 10.00 0.000000 + 0.000000 -> 0.255045 (ok)
Loadcase: 5003 3 50 6.33 6.67 0.000000 + 0.000000 -> 0.151464 (ok)
Loadcase: 5005 5 50 3.80 4.00 0.000000 + 0.000000 -> 0.116979 (ok)
Loadcase: 5010 10 50 1.90 2.00 0.000000 + 0.000000 -> 0.081181 (ok)
I simply want the floats to be right aligned and some spaces inserted where necessary.我只是希望浮点数正确对齐,并在必要时插入一些空格。 I really basically want the table to be nicely aligned.
我真的基本上希望桌子很好地对齐。 My guess of writing %2.2f seems to be ignored.
我对 %2.2f 的猜测似乎被忽略了。
I cannot use numpy for technical reasons.由于技术原因,我不能使用 numpy。
You're misunderstanding what %2.2f
means. 您误解了
%2.2f
含义。 It means "give the float 2 columns total, and display 2 positions after the radix point". 这表示“给浮点数总共2列,并在小数点后显示2个位置”。 Perhaps you want
%5.2f
instead. 也许您想要
%5.2f
代替。
The syntax is 语法是
% fieldwidth . precision conversiontype
So in you want to leave some space, and show 2 decimals, try 因此,在您要留一些空间并显示2个小数的情况下,请尝试
%8.2f
See the Python documentation for a full overview. 有关完整概述,请参见Python文档 。
The format string "%4.2f"
says: format with 2 digits after radix point and use at least 4 characters for the full string . 格式字符串
"%4.2f"
说:在小数点后加2位数字的格式, 完整字符串至少使用4个字符。 So 所以
"%4.2f" % 1.1 --> " 1.1"
"%4.2f" % 11.1 --> "11.1"
"%4.2f" % 111.1 --> "111.1"
In your case you have the set the 4
above high enough. 在您的情况下,您已将上述
4
设置为足够高。
I am using pycharm professional我正在使用 pycharm 专业版
this is my code for converting fahrenheit from Celsius这是我从摄氏度转换华氏度的代码
def temperature():
print("Celsius_Degree Fahrenheit_Degree")
print("============== =================")
for Celsius in range(0, 101, 1):
fahrenheit = (9/5) * Celsius + 32
print("{:>5.1f} C {:>5.1f} F".format(Celsius, fahrenheit))
temperature()温度()
so when I change :>5.1f to %5.1f why am I getting KeyError: '%5'因此,当我将 :>5.1f 更改为 %5.1f 时,为什么会出现 KeyError: '%5'
I have added the 2 output screenshot of the error as well a screenshot of no error, please explain;我已经添加了错误的2输出截图以及没有错误的截图,请解释; I am getting confused which one I am supposed to use %5.1f or :>5.1f Error with writing %5.1f no error with writing :>5.1f
我很困惑我应该使用哪个 %5.1f 或 :>5.1f写入 %5.1f 时出错 写入时没有错误 :>5.1f
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.