2

Can someone please explain what's the asterisk and !r doing here?

I just came across this snippet on internet. It's some class called Polynomial that is instantiated with three coefficients. I looked through internet and figured that __repr__ is a representation, but how exactly does asterisk and !r works in here?

def __repr__(self):
    return 'Polynomial(*{!r})'.format(self.coeffs)
Selcuk
  • 57,004
  • 12
  • 102
  • 110
user8740527
  • 67
  • 2
  • 7
  • 1
    That will raise an error as it is an invalid format specifier. Are you sure you copied the code correctly? – Selcuk Jun 11 '19 at 03:01
  • Possible duplicate of [How does an asterisk \`\*\` work in the string formatting method \`.format(\*) \` in Python 3?](https://stackoverflow.com/questions/52475322/how-does-an-asterisk-work-in-the-string-formatting-method-format-in-p) – ggorlen Jun 11 '19 at 03:31
  • @Selcuk Yes, I copied it correctly. I will just edit my original post to add the entire code if that helps. – user8740527 Jun 11 '19 at 04:05
  • @Selcuk Link: https://www.youtube.com/watch?v=cKPlPJyQrt4. It's at exact 12 minutes the person is using it. – user8740527 Jun 11 '19 at 04:12
  • Ok, you seem to have been missing the closing curly brace. After your edit it looks fine. – Selcuk Jun 11 '19 at 04:17
  • Possible duplicate of [What does \*\* (double star/asterisk) and \* (star/asterisk) do for parameters?](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) – Shanteshwar Inde Jun 11 '19 at 05:36
  • @Selcuk Yes, my apologies I missed that. – user8740527 Jun 12 '19 at 00:23
  • 1
    @Selcuk Thank you again. :) – user8740527 Jun 12 '19 at 21:37

1 Answers1

1

The asterisk has no special meaning there; it simply prints the asterisk character in the formatted string.

!r is a conversion flag that calls the .repr() of the argument. So the resulting string for the format string in your question would be equivalent to the following:

'Polynomial(*' + repr(self.coeffs) + ')'
Selcuk
  • 57,004
  • 12
  • 102
  • 110