【发布时间】:2020-07-18 02:11:03
【问题描述】:
我无法找出我在 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”添加到最后一个以使其工作?
【问题讨论】:
-
为什么不使用格式选项? eg:
print('{:.3f}'.format(0.1))3表示保留小数点后3位。
标签: python python-3.x string concatenation string-concatenation