I have some code I found during a classes tutorial and I can’t understand how one line is working (although it does work). It is the fstring line, the part in question is the “:+” at the end of the second set of curly braces, I don’t understand how the :+ can make the needed “+” in the string format appear before the contents of the curly braces when the string is outputted.
Code
class Vector:
def __init__(self, x_comp, y_comp):
self.x_comp = x_comp
self.y_comp = y_comp
def __str__(self):
# By default, sign of +ve number is not displayed
# Using `+`, sign is always displayed
return f'{self.x_comp}i{self.y_comp:+}j'
v = Vector(3,4)
print(str(v))
print(v)
Output
3i+4j
3i+4j