如何在Python 3中在f-字符串中添加花括号?

7
我有这段代码。
class = "maximum"
s = f"""The code for {class} is {3854-st56}"""
print(s)

我想要输出以下内容:
>> The code for maximum is {3854-st56}

但是f-string不能识别3854-st56周围的花括号,而是认为我正在尝试输入实际的Python代码。我该如何让f-string识别这些花括号为字符串文字?
2个回答

10

6

如果您正在分配变量值,则需要使用两次花括号,如果您正在放置值,则只需使用一次:

Class = "maximum"
s = f"""The code for {{{Class}}} is {{'3854-st56'}}"""
print(s)

The code for {maximum} is {3854-st56}

使用双大括号 {{ 或 }} 使您的代码变为:sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", prop.Type, prop.Name));// 对于 prop.Type 为 "Foo" 和 prop.Name 为 "Bar" 的情况,结果将是: // public Foo Bar { get; private set; } - Pratham_Amitabh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接