How do I use string formatting to show BOTH leading zeros and precision of 3?

孤街浪徒 提交于 2020-08-20 23:48:26

问题


I'm trying to represent a number with leading and trailing zeros so that the total width is 7 including the decimal point. For example, I want to represent "5" as "005.000". It seems that string formatting will let me do one or the other but not both. Here's the output I get in Ipython illustrating my problem:

In [1]: '%.3f'%5
Out[1]: '5.000'

In [2]: '%03.f'%5
Out[2]: '005'

In [3]: '%03.3f'%5
Out[3]: '5.000'

Line 1 and 2 are doing exactly what I would expect. Line 3 just ignores the fact that I want leading zeros. Any ideas? Thanks!


回答1:


The first number is the total number of digits, including decimal point.

>>> '%07.3f' % 5
'005.000'

Important Note: Both decimal points (.) and minus signs (-) are included in the count.




回答2:


[Edit: Gah, beaten again]

'%07.3F'%5

The first number is the total field width.




回答3:


This took me a second to figure out how to do @nosklo's way but with the .format() and being nested.

Since I could not find an example anywhere else atm I am sharing here.

Example using "{}".format(a)

Python 2

>>> a = 5
>>> print "{}".format('%07.3F' % a)
005.000
>>> print("{}".format('%07.3F' % a))
005.000

Python 3

More python3 way, created from docs, but Both work as intended.

Pay attention to the % vs the : and the placement of the format is different in python3.

>>> a = 5
>>> print("{:07.3F}".format(a))
005.000
>>> a = 5
>>> print("Your Number is formatted: {:07.3F}".format(a))
Your Number is formatted: 005.000

Example using "{}".format(a) Nested

Then expanding that to fit my code, that was nested .format()'s:

print("{}: TimeElapsed: {} Seconds, Clicks: {} x {} "
      "= {} clicks.".format(_now(),
                            "{:07.3F}".format((end -
                                               start).total_seconds()),
                            clicks, _ + 1, ((_ + 1) * clicks),
                            )
      )

Which formats everything the way I wanted.

Result

20180912_234006: TimeElapsed: 002.475 Seconds, Clicks: 25 + 50 = 75 clicks.

Important Things To Note:

  • @babbitt: The first number is the total field width.

  • @meawoppl: This also counts the minus sign!...



来源:https://stackoverflow.com/questions/3604587/how-do-i-use-string-formatting-to-show-both-leading-zeros-and-precision-of-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!