Change default float print format

后端 未结 7 561
无人共我
无人共我 2020-12-01 16:44

I\'ve some lists and more complex structures containing floats. When printing them, I see the floats with a lot of decimal digits, but when printing, I don\'t need all of th

7条回答
  •  盖世英雄少女心
    2020-12-01 17:10

    You are not allowed to monkeypatch C types, like Ignacio said.

    However, if you are terribly pressed in doing so and you know some C, you could go modify the Python interpreter source code yourself, then recompile it into a custom solution. Once I modified one of the standard behaviors for lists and it was only a moderate pain.

    I suggest you find a better solution, such as just printing the floats with the "%0.2f" printf notation:

    for item in mylist:
        print '%0.2f' % item,
    

    or

    print " ".join('%0.2f' % item for item in mylist)
    

提交回复
热议问题