Python浮动到字符串:如何获得'0.03'但'-.03'

xnx*_*xnx 1 python string floating-point

是否有一种快速方法可以将-0.99和+0.99之间的浮点数转换为总是占用4个字符:即正值变为例如'0.03'而负值变为例如'-.03',而没有前导零?显然我能做到

s = '%4.2f' % n
if s[0] == '-':
    s = '-%s' % s[2:]
Run Code Online (Sandbox Code Playgroud)

但也许有些stackoverflowers知道Python的快捷方式?

Bjö*_*lex 5

好吧,你可以这样做:

"{0: 3.2f}".format(n)
Run Code Online (Sandbox Code Playgroud)

空格表示对于正数,应打印空格,对于负数,则表示符号.这样,它们总是采用相同的宽度.