1

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
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Windy71
  • 851
  • 1
  • 9
  • 30
  • 2
    I believe including the `+` tells the string formatter to always include the number's sign when formatting as string. Normally, a positive number would not have its sign symbol (`+`) shown. – Matthew R. Nov 28 '20 at 18:58
  • Is that why it needed a colon before it? – Windy71 Nov 28 '20 at 19:00
  • 1
    Yes. When using f-strings, you can put the string format after a colon within the curly braces. For example, for a floating point value you could using `{my_float_val:.3f}` to show it with 3 places after the decimal point. – Matthew R. Nov 28 '20 at 19:02
  • I found this after reading your comment, thank you Matthew https://stackoverflow.com/questions/53583596/using-f-string-to-insert-characters-or-symbols – Windy71 Nov 28 '20 at 19:02
  • 1
    If you paste that as an answer I’ll accept it, thanks. – Windy71 Nov 28 '20 at 19:02

2 Answers2

2
'+'  - indicates that a sign should be used for both
       positive as well as negative numbers
'-'  - indicates that a sign should be used only for negative
       numbers (this is the default behavior)
' '  - indicates that a leading space should be used on
       positive numbers

https://www.python.org/dev/peps/pep-3101/#standard-format-specifiers

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Etoneja
  • 1,023
  • 1
  • 8
  • 15
2

Including the + tells the string formatter to always include the number's sign when formatting as string. Normally, a positive number would not have its sign symbol (+) shown.

Matthew R.
  • 615
  • 4
  • 12