Python Forum

Full Version: Formating for __repr__
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am banging my head against the wall. I have tried so many different format things to get this to work and cannot figure it out. 
I am not so sharp at making strings look exactly like I want them to. Hopefully someone can help me. Thanks. Here's the code I've tried in it's current format.
#I need it to look exactly like this:
#"3kg (0,6.37e+06,0) (0,0,0)"
formated = '({:.3g},{:.3g},{:.3g})'.format(self.mass, self.position, self.velocity)
return formated

#Also tried this:
formatted = '"{1:8.2f},{1:8.2f},{1:8.2f}"'.format(self.mass, self.position, self.velocity)
So, what did you get that was not to your liking?

I don't know what specification g means, but in line 7 you'll only get self.position - 3 times. Number before colon - may be omitted in most cases - tells which positional argument to use that specification for. Either remove it - or replace with 0, 1, 2 respectively
It would help if we could see the data you are trying to format. It looks from your desired output that position and velocity are tuples of the three dimensional components of position and velocity. You will have to format each tuple separately, and then combine the results in with the formatting of any non-tuple data.
position = (801, 23, 2.718281828)
position_text = '({:3g}, {:3g}, {:3g})'.format(*position)
The * syntax converts a sequence into a sequence of parameters.
Maybe it would help if I give you the entire __repr__ function.  The data being passed as parameters is mass = 3, position = (0,6.37e+06,0), and velocity = (0,0,0)
def __repr__(self):
        #Representation Call
        #"3kg (0,6.37e+06,0) (0,0,0)"
        formatted = '{1:.6f},({1:.6f},{1:.6f},{1:.6f}),({1:.6f},{1:.6f},{1:.6f})'.format(self.mass, self.position, self.velocity)
        
        print(formatted) #This was for testing. 
        return formatted
I mostly have it now. Thought I would follow up for anyone else and to see how to align it all correctly. Here's the code:

formatted = '{0!s:6s},{1!s:6s},{2!s:6s}'.format(mass, position, velocity)
Input


str(melon) == "3kg (0,6.37e+06,0) (0,0,0)"

I get 3kg (0,6.37e+06,0) (0,0,0), which is correct.


When I pass this
str(earth) == "5.97e+24kg (0,0,0) (0,0,0)"

I get 5.9736kg (0,0,0) (0,0,0), which you can see is not correct.
Most of what you are doing is unnecessary. Take {0!s:6s}. The 0 says take the first parameter, which is what it's going to do anyway for the first set of braces. The !s says to use string formatting, which is the default. The second 's' says (again) to use string formatting. So all you have really asked for is :6, which means width of six. If you want only exponential format, you want :6e. If you want only two digits of precision, you want :6.2e. It is all explained in the string formatting documentation: https://docs.python.org/3/library/string...ing-syntax