Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

python - Print floating point values without leading zero

Trying to use a format specifier to print a float that will be less than 1 without the leading zero. I came up with a bit of a hack but I assume there is a way to just drop the leading zero in the format specifier. I couldn't find it in the docs.

Issue

>>> k = .1337
>>> print "%.4f" % k
'0.1337'

Hack

>>> print ("%.4f" % k) [1:]
'.1337'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is another way:

>>> ("%.4f" % k).lstrip('0')
'.1337'

It is slightly more general than [1:] in that it also works with numbers >=1.

Neither method correctly handles negative numbers, however. The following is better in this respect:

>>> re.sub('0(?=[.])', '', ("%0.4f" % -k))
'-.1337'

Not particularly elegant, but right now I can't think of a better method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...