如何连接四舍五入的数字字符串python? - python

我在弄清楚如何在python中连接字符串时遇到错误。

我们的目标是将数字格式化为字符串,然后以一致的长度进行打印。

我编写了以下代码:

def numPrint(number,roundplace):
    num = round(number, roundplace)
    if num > 0:
        output = ('+' + str(num))
    elif num < 0:
        output = (str(num))
    else:
        output = (' 0.' + '0' * roundplace)    

    if len(output) < (3 + roundplace):
        output2 = (output + '0')
    else:
        output2 = output

    return output2

print(numPrint(0.001, 3))
print(numPrint(0, 3))
print(numPrint(-0.0019, 3))
print(numPrint(-0.01, 3))
print(numPrint(0.1, 3))

我希望它能打印:

+0.001
 0.000
-0.002
-0.010
+0.100

但是,我越来越

+0.001
 0.000
-0.002
-0.010
+0.10

如何在最后一个数字上加上“ 0”以使其正常工作?

参考方案

您只是忘记了将output2的零相乘:

if len(output) < (3 + roundplace):
    output2 = (output + ('0'*(3 + roundplace - len(output))))
else:
    output2 = output

或者,如果您不介意使用内置功能:

output2 = output.ljust(3 + roundplace, '0')

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python uuid4,如何限制唯一字符的长度 - python

在Python中,我正在使用uuid4()方法创建唯一的字符集。但是我找不到将其限制为10或8个字符的方法。有什么办法吗?uuid4()ffc69c1b-9d87-4c19-8dac-c09ca857e3fc谢谢。 参考方案 尝试:x = uuid4() str(x)[:8] 输出:"ffc69c1b" Is there a way to…