Home > other >  Pad float with zeros according to maximum length in list
Pad float with zeros according to maximum length in list

Time:04-06

I have a list:

ls = [1.0, 2.11, 3.981329, -15.11]

I want to add zeros to decimal places of each element so that all values have the same length as the value that has maximum length. So the output should be:

[1.000000, 2.110000, 3.981329, -15.110000]

How can I do this?

CodePudding user response:

You can easily output to a desired number of decimal places,

print("[" ", ".join(f"{el:.8f}" for el in ls) "]")

using f-strings.

The value of getting the maximum number of visible decimal places is something you might want to consider carefully - it isn't obvious why you would do that in a simulated raw output like this. You can get a suitable number by a string analysis but it isn't pretty.

dp = 0
for el in ls:
    op = str(el)
    if "." in op:
        dpi = len(op)-1 - op.find(".")
        if dpi > dp: dp = dpi
print("[" ", ".join(f"{el:.{dp}f}" for el in ls) "]")

CodePudding user response:

Here's an alternative solution. Note that the nums will be strings:

ls = [1.0, 2.11, 3.981329, -15.11]

dps = lambda x: len(x) - x.index(".") - 1

max_dp = max([dps(str(i)) for i in ls])

new_ls = [f"%.{max_dp}f"%i for i in ls]

print(new_ls)

Output:

['1.000000', '2.110000', '3.981329', '-15.110000']
  • Related