我在课堂教程中发现了一些代码,我不明白一行是如何工作的(尽管它确实工作(。这是fstring行,有问题的部分是第二组大括号末尾的":+",我不明白:+如何在输出字符串时使字符串格式中所需的"+"出现在大括号的内容之前。
代码
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)
输出
3i+4j
3i+4j
包含+
,这会告诉字符串格式化程序在格式化为字符串时始终包含数字的符号。通常,正数不会显示其符号(+
(。
- 有关f-string语法的更多信息,请参阅格式化字符串文字
- 有关字符串格式说明符引用(包括
+
(,请参阅格式规范迷你语言
'+' - 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-格式说明符