F 带特殊字符的字符串

F String With Special Characters

我想使用 f 字符串文字打印以下内容。它将是一个函数 运行 并且 apples 将是参数之一。我希望它包含方括号。

"I like [apples] because they are green"

我试过以下代码:

"I like {} because they are green".format("apples")

上面的代码打印:

I like apples because they are green

如何将方括号 [ ] 或其他特殊字符(例如 < >)插入到 f 字符串文字中?

有几种可能的方法可以做到这一点:

"I like [{}] because they are green".format("apples") 要么 "I like {} because they are green".format("[apples]").

如果您想使用实际的特殊字符而不是方括号,您只需要在适当的地方转义即可:

"I like {} because they are green".format("\"apples\"").

此外,如果您想使用实际的 f 弦,您可以执行与上述相同的操作,但格式为:

f"I like {'[apples]'} because they are green"

但请确保将括号内的双引号切换为单引号,以避免提前结束字符串造成麻烦。

这里有一些关于如何在 f 字符串中使用特殊字符的建议。

  1. 如果要打印

Hello "world", how are you

var1 = "world"
print(f"Hello \"{var1}\", how are you") 
  1. 打印:

Hello {world}, how are you

world 是一个变量

var1 = world 
print(f"Hello {{var1}}, how are you")
  1. 打印:

Hello {world}, how are you

世界是一个常数

print(f"Hello ""{world""}, how are you")

打印: 你好{world},你好吗

world 是一个变量

var1 = world 
print(f"Hello {{var1}}, how are you")

不正确。您必须添加一个额外的括号

var1 = world 
print(f"Hello {{{var1}}}, how are you")

因为在 f-string 双括号绘制单括号