Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...