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'
print( '{:,g}'. format( X ) worked for me to output 3 where X = 6 / 2 and when X = 5 / 2 I got an output of 2.5 as expected. old question, but.. print("%s"%3.140) gives you what you want.
If you want the final result to be an integer or a float, simply convert it after using int(out) or float(out) . Edit: if you want to change the precision (has to be fixed precision to account for trailing zeros), you just need to change the int appearing in the f-string: out = f'{x:.
Use the str. zfill() Function to Display a Number With Leading Zeros in Python. The str. zfill(width) function is utilized to return the numeric string; its zeros are automatically filled at the left side of the given width , which is the sole attribute that the function takes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With