如何使用 f-string 在一组花括号的内容之前定位一个字符
How to position a character before the contents of a set of curly braces using f-string
我在 类 教程中发现了一些代码,但我无法理解其中一行是如何工作的(尽管它确实有效)。
这是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
'+' - 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
包括 +
告诉字符串格式化程序在格式化为字符串时始终包含数字的符号。通常,正数不会显示其符号 (+
)。
- 有关 f 字符串语法的更多信息,请参阅 Formatted string literals。
- 有关字符串格式说明符的参考(包括提及
+
),请参阅 Format Specification Mini-Language。
我在 类 教程中发现了一些代码,但我无法理解其中一行是如何工作的(尽管它确实有效)。 这是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
'+' - 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
包括 +
告诉字符串格式化程序在格式化为字符串时始终包含数字的符号。通常,正数不会显示其符号 (+
)。
- 有关 f 字符串语法的更多信息,请参阅 Formatted string literals。
- 有关字符串格式说明符的参考(包括提及
+
),请参阅 Format Specification Mini-Language。