Formatting Python formatting with leading zeros and optional decimal places

I am trying to format some numbers in Python as follows:

(number) -> (formatted number)
1 -> 01
10 -> 10
1.1 -> 01.1
10.1 -> 10.1
1.1234 -> 01.1

What formatting specification can I use for this?

What I tried: {:04.1f}does not work correctly if there is no decimal part, but {:0>2}works only for integers, {:0.2g}approaches, but does not add a leading zero and {:0>4.2g}adds too many zeros if there is no decimal part.

+4
source share
3 answers

Since you do not want a decimal point for special cases, formatting rules do not exist.

Workaround:

"{:04.1f}".format(number).replace(".0", "")
+5
source

I would say if your number will be a whole or a float:

if isinstance(number, int):
    print('{:0>2}'.format(number))
elif isinstance(number, float):
    print('{:04.1f}'.format(number))
+1
source

Hackish answer:

l = [1, 10, 1.1, 10.1, 1.1234]
s = lambda n: '{{{}}}'.format(':04.1f' if isinstance(n, float) else ':02').format(n)

for i in l:
    print(s(i))

# 01
# 10
# 01.1
# 10.1
# 01.1

- . .

0

Source: https://habr.com/ru/post/1692606/


All Articles