简体   繁体   English

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

[英]How do I concatenate strings of rounded numbers python?

I'm having trouble figuring out an error in how I'm concatenating a string in python.我无法弄清楚如何在 python 中连接字符串时出现错误。

The goal is to format numbers into a string which I can print with a consistent length.目标是将数字格式化为可以以一致长度打印的字符串。

I've written the following code:我编写了以下代码:

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))

I expect it to print:我希望它打印:

+0.001
 0.000
-0.002
-0.010
+0.100

however, I'm getting但是,我得到

+0.001
 0.000
-0.002
-0.010
+0.10

How do I add "0"'s to the last one to get it to work?如何将“0”添加到最后一个以使其工作?

You just forgot to multiply the zeros for output2 :您只是忘记将output2的零相乘:

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

Or if you don't mind using built-in function:或者,如果您不介意使用内置 function:

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

Try this:尝试这个:


def num_print(number, roundplace):
    sign = '+' if number != 0 else ' '
    output = '{num:{sign}.{rp}f}'.format(num=number, sign=sign, rp=roundplace) # python3
#     output = f'{number:{sign}.{roundplace}f}' # python 3.6 +
    return output

+0.001
 0.000
-0.002
-0.010
+0.100

You can use string formatting if you just want to display the numbers.如果您只想显示数字,可以使用字符串格式。

def format_number(number, minimum_digits=1, decimal_places=2):
    format_string = '{{: {}.{}f}}'.format(minimum_digits, decimal_places)
    result = format_string.format(number)
    if number:
        result = result.replace(' ', '+', 1)  # Technically you can use '+' above but your desired output requires zero to have no sign
    return result

print(format_number(0.001, minimum_digits=1, decimal_places=3))
print(format_number(0, minimum_digits=1, decimal_places=3))
print(format_number(-0.0019, minimum_digits=1, decimal_places=3))
print(format_number(-0.01, minimum_digits=1, decimal_places=3))
print(format_number(0.1, minimum_digits=1, decimal_places=3))
+0.001
 0.000
-0.002
-0.010
+0.100

Try using the .format() string method, it's really useful and handy.尝试使用.format()字符串方法,它非常有用且方便。

def numPrint(number,roundPlace):
   return "{{:+.{}f}}".format(roundPlace).format(number)

You can use built in format function like this:您可以像这样使用内置格式 function :

print("{:+.4f}".format(0.09))

Look here for more detail on format specification:在此处查看有关格式规范的更多详细信息:

https://docs.python.org/3.4/library/string.html#formatexamples https://docs.python.org/3.4/library/string.html#formatexamples

This will work:这将起作用:

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)    

    while len(output) < (3 + roundplace): # previously you stopped after adding one trailing 0
        output = (output + '0')

    return output

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

For Python 3.6+ you may use an f-string :对于 Python 3.6+,您可以使用f-string

def num_print(number, round_place):
    return f"{number:{'+' if number else ' '}.{round_place}f}"

(I intentionally changed the names of your function and its second parameter from numPrint and roundPlace to num_print and round_place to be in concordance with PEP 8 - Style Guide: Function and Variable Names .) (我故意将您的 function 的名称及其第二个参数从numPrintroundPlacenum_printround_place以符合PEP 8 - 样式指南:Function 和变量名称。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM