在 Python 中转换为科学记数法 (A × 10^B) [英] Convert to scientific notation in Python (A × 10^B)

查看:115
本文介绍了在 Python 中转换为科学记数法 (A × 10^B)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这个问题来帮助我创建一个科学记数法函数,但是我想要这个:4.08 x 10^10 而不是 4.08E+10.所以我做了一个工作函数,如下所示:

I was using this question to help me create a Scientific Notation function, however instead of 4.08E+10 I wanted this: 4.08 x 10^10. So I made a working function like so:

def SciNotation(num,sig):
    x='%.2e'  %num  #<-- Instead of 2, input sig here
    x= x.split('e')
    if (x[1])[0] == "-":
        return x[0]+" x 10^"+ x[1].lstrip('0')
    else:
        return x[0]+" x 10^"+ (x[1])[1:].lstrip('0')

num = float(raw_input("Enter number: "))
sig = raw_input("Enter significant figures: ")
print SciNotation(num,2)

这个函数,当输入 99999 时,输出 1.00 x 10^5(2 个有效数字).但是,我需要使用我的 sig 变量(用户输入的有效数字的数量).我知道我必须将 sig 变量输入到代码的第 2 行,但我似乎无法开始工作.

This function, when given an input of 99999 will print an output of 1.00 x 10^5 (2 significant figures). However, I need to make use of my sig variable (# of significant figures inputted by user). I know I have to input the sig variable into Line 2 of my code but I can't seem to get to work.

到目前为止我已经尝试过(输入 num=99999,sig=2):

So far I have tried (with inputs num=99999, sig=2):

  1. x='%.%de' %(num,sig)

TypeError: 在字符串格式化期间并非所有参数都被转换

TypeError: not all arguments converted during string formatting

x='%d.%de' %(num,sig)

x = 99999.2e(错误输出)

x = 99999.2e (incorrect output)

x='{0}.{1}e'.format(num,sig)

x = 99999.0.2e(错误输出)

x = 99999.0.2e (incorrect output)

任何帮助将不胜感激!

推荐答案

使用 新的字符串格式.无论如何,您使用的旧样式已被弃用:

Use the new string formatting. The old style you're using is deprecated anyway:

In [1]: "{0:.{1}e}".format(3.0, 5)
Out[1]: '3.00000e+00'

这篇关于在 Python 中转换为科学记数法 (A × 10^B)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆