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
I ran into this issue today, and I came up with a different solution. If you're worried about what it looks like when printed, you can replace the stdout file object with a custom one that, when write() is called, searches for any things that look like floats, and replaces them with your own format for them.
class ProcessedFile(object):
def __init__(self, parent, func):
"""Wraps 'parent', which should be a file-like object,
so that calls to our write transforms the passed-in
string with func, and then writes it with the parent."""
self.parent = parent
self.func = func
def write(self, str):
"""Applies self.func to the passed in string and calls
the parent to write the result."""
return self.parent.write(self.func(str))
def writelines(self, text):
"""Just calls the write() method multiple times."""
for s in sequence_of_strings:
self.write(s)
def __getattr__(self, key):
"""Default to the parent for any other methods."""
return getattr(self.parent, key)
if __name__ == "__main__":
import re
import sys
#Define a function that recognises float-like strings, converts them
#to floats, and then replaces them with 1.2e formatted strings.
pattern = re.compile(r"\b\d+\.\d*\b")
def reformat_float(input):
return re.subn(pattern, lambda match: ("{:1.2e}".format(float(match.group()))), input)[0]
#Use this function with the above class to transform sys.stdout.
#You could write a context manager for this.
sys.stdout = ProcessedFile(sys.stdout, reformat_float)
print -1.23456
# -1.23e+00
print [1.23456] * 6
# [1.23e+00, 1.23e+00, 1.23e+00, 1.23e+00, 1.23e+00, 1.23e+00]
print "The speed of light is 299792458.0 m/s."
# The speed of light is 3.00e+08 m/s.
sys.stdout = sys.stdout.parent
print "Back to our normal formatting: 1.23456"
# Back to our normal formatting: 1.23456
It's no good if you're just putting numbers into a string, but eventually you'll probably want to write that string to some sort of file somewhere, and you may be able to wrap that file with the above object. Obviously there's a bit of a performance overhead.
Fair warning: I haven't tested this in Python 3, I have no idea if it would work.