Sorry, Python doesn't provide global settings to control formatting. If you don't want to display floats at their full precision then you need to format them explicitly. I suppose that's not so convenient when you print a collection containing floats. However, the __repr__
of Python's collection objects (tuple, list, dict, set) is primarily intended for displaying these objects to programmers, not to users. It is expected that you will format such objects if you intend to display them to users, not just dump them to the terminal.
If you want to use the same formatting in multiple places it may be worthwhile to define a function. Eg,
max_float_digits = 4
def rounded(val):
return '{:.{}f}'.format(val, max_float_digits)
data = [
('user_ctr', 2253.459088429824), ('user_clicks', 2042.3175666666664),
('t_avg_sim', 176.83513843049306), ('item_ctr', 137.6051319164618),
('item_age', 128.52122456437388), ('t_max_sim', 126.23752629310347),
('item_read_time', 46.94452635514022), ('clicks', 26.368489035532996),
('likes', 15.43922933884298), ('c_max_sim', 14.761540559999993),
('no_clicks', 13.020515220883516), ('c_avg_sim', 10.969965476190472),
('user_read_time', 10.21293115646259), ('user_age', 9.776781678832117),
]
out_data = [(key, rounded(val)) for key, val in data]
for row in out_data:
print(row)
output
('user_ctr', '2253.4591')
('user_clicks', '2042.3176')
('t_avg_sim', '176.8351')
('item_ctr', '137.6051')
('item_age', '128.5212')
('t_max_sim', '126.2375')
('item_read_time', '46.9445')
('clicks', '26.3685')
('likes', '15.4392')
('c_max_sim', '14.7615')
('no_clicks', '13.0205')
('c_avg_sim', '10.9700')
('user_read_time', '10.2129')
('user_age', '9.7768')
If you actually want the string representation of the list, and you want it to look as shown in the question, you can use the built-in round
function.
output = [(key, round(val, max_float_digits)) for key, val in data]
print(output)
output
[('user_ctr', 2253.4591), ('user_clicks', 2042.3176), ('t_avg_sim', 176.8351), ('item_ctr', 137.6051), ('item_age', 128.5212), ('t_max_sim', 126.2375), ('item_read_time', 46.9445), ('clicks', 26.3685), ('likes', 15.4392), ('c_max_sim', 14.7615), ('no_clicks', 13.0205), ('c_avg_sim', 10.97), ('user_read_time', 10.2129), ('user_age', 9.7768)]
To turn any object into its string representation, pass it to repr
or str
, eg
s = repr(output)