字符串格式:科学记数法以 0 开头.对于正数,以 - 开头.对于负数 [英] String format: Start scientific notation with 0. for positive number, with -. for negative number
本文介绍了字符串格式:科学记数法以 0 开头.对于正数,以 - 开头.对于负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用固定指数格式格式化数字列表:
I want to format a list of numbers with a fixed exponential format:
0.xxxxxxxxxxxxEsee
如果数字为负数,则应将 0 替换为 0:
If the number is negative, the 0 should be substituted with a 0:
-.xxxxxxxxxxxxEsee
我可以用格式字符串来完成吗?例如
Can I accomplish this with a format string? E.g.
output.write('{:+016.10E}{:+016.10E}{:+016.10E}\n'.format(a,b,c))
效果很好,但没有满足零的要求,并且确实给出了前导 0.
.
works nice, but does not fullfil the drop-the-zero requirement and also does give a leading 0.
.
一个示例输出是
-.704411727284E+00-.166021493805E-010.964452299466E-020.229380762349E-07
-.103417103118E-05-.269314547877E-040.140398741573E-020.000000000000E+00
0.000000000000E+00-.704410110737E+00-.166019042695E-010.964139641580E-02
-.196412061468E-070.125311265867E-050.269427086293E-04-.140464403693E-02
0.000000000000E+000.000000000000E+00-.496237902548E-020.505395880357E-03
-.332217159196E-02-.192047286272E-030.139005979401E-02-.146291733047E-03
0.947012666403E-030.000000000000E+000.000000000000E+00-.496237514486E-02
0.505449126498E-03-.332395118617E-020.192048881658E-03-.139035528110E-02
推荐答案
这个怎么样?
import re
# "fix" a number in exponential format
def fixexp(foo):
# shift the decimal point
foo = re.sub(r"(\d)\.", r".\1", foo)
# add 0 for positive numbers
foo = re.sub(r" \.", r"0.", foo)
# increase exponent by 1
exp = re.search(r"E([+-]\d+)", foo)
newexp = "E{:+03}".format(int(exp.group(1))+1)
foo = re.sub(r"E([+-]\d+)", newexp, foo)
return foo
nums = [ -0.704411727284, -1.66021493805, 0.00964452299466, 0.0000000229380762349, -0.00000103417103118, -0.0000269314547877, 0.00140398741573 ]
# print the numbers in rows of 4
line = ""
for i in range(len(nums)):
num = "{:18.11E}".format(nums[i])
num = fixexp(num)
line += num
if (i%4 == 3 or i == len(nums)-1):
print line
line = ""
输出:
-.704411727284E+00-.166021493805E+010.964452299466E-020.229380762349E-07
-.103417103118E-05-.269314547877E-040.140398741573E-02
这篇关于字符串格式:科学记数法以 0 开头.对于正数,以 - 开头.对于负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文