How to remove leading zeros with “{ }”.format() wh

2019-08-17 04:28发布

I'm looking for a way to output floating point numbers as strings, formatted without leading zeros. Is there a way to do this with '{ }'.format()? I searched the internet but didn't find anything. Did I just miss it or is it impossible? What I have in mind is basically

some_number = 0.314
string = '{x}'.format(some_number)

that gives the output string '.314'.. The task is: find x.

Of course one could do this with lstrip as described e.g. here or similar here:

In [93]: str(0.314).lstrip('0')
Out[93]: '.314'

but it would be more convenient to use only the '{ }'.format() method in my opinion. Since I can use that for other formatting options, optionally calling lstrip demands additional lines of code.

2条回答
疯言疯语
2楼-- · 2019-08-17 04:51

if you want to just strip 0 from floating numbers you could use this "hack"

"." + str(0.314).split("0.")[-1]

this is in no way an elegant solution, but it will get the job done

also if you want to use .format as well you don't need another line, you could just

"." +str(0.314).split("0.")[-1].format('')
查看更多
够拽才男人
3楼-- · 2019-08-17 05:00

If you want to use format(), then try as below.

print("Hello {0}, your balance is {1}.".format("Adam", "0.314".lstrip('0')))

Just use lstrip() within format function, you don't need to write additional line of code.

查看更多
登录 后发表回答