【问题标题】:F String With Special CharactersF 带特殊字符的字符串
【发布时间】:2019-08-05 16:32:35
【问题描述】:

我想使用 f 字符串文字打印以下内容。它将在一个函数中运行,而苹果将是参数之一。我希望它包含方括号。

"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...
  • 另一种方式(有点神奇,但很好)是这样的:"I like {} because they are green".format(["apples"])。它添加了括号,因为您传递了一个列表,而不仅仅是原子字符串。
  • 在前面的注释的基础上,格式化字符串中唯一真正“特殊”的字符(除了转义字符,就像在任何其他字符串中一样)是占位符字符 {} .如果您想按字面意思使用它们,则必须复制它们,例如,要获得I like {apples},您需要使用"I like {{{}}}".format("apples")(三对大括号,两对用于文字大括号,一对用于占位符)。

标签: python string f-string


【解决方案1】:

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

"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"

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

【讨论】:

    【解决方案2】:

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

    1. 如果你想打印

    你好“世界”,你好吗

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

    你好,{world},你好吗

    世界是一个变量

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

    你好,{world},你好吗

    世界是一个常数

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

    【讨论】:

      猜你喜欢
      • 2020-07-12
      • 2012-03-23
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      • 2017-05-05
      • 2020-06-04
      • 2011-06-10
      • 1970-01-01
      相关资源
      最近更新 更多