【问题标题】:Is there a difference between "f" and "F" in Python string formatting?Python字符串格式中的“f”和“F”有区别吗?
【发布时间】:2020-06-09 16:08:28
【问题描述】:

为了在 Python 3.6+ 中格式化字符串,我通常使用小写的“f”选项来包含变量。例如:

response = requests.get(f'{base_url}/{endpoint}?fields={field_list}')

我最近看到我的一位同事总是使用大写“F”来代替。像这样:

response = requests.get(F'{base_url}/{endpoint}?fields={field_list}')


小写“f”和大写“F”有区别吗?如果是,您什么时候使用它们?

【问题讨论】:

  • AFAIK,“F”和“f”没有区别。
  • 小写的f 更容易输入,因为它不需要按住 Shift 键。

标签: python string string-formatting


【解决方案1】:

正如PEP 498 章节Specification 中所解释的,两者都被接受,并且应该没有区别。

In source code, f-strings are string literals that are prefixed by the letter 'f' or 'F'. Everywhere this PEP uses 'f', 'F' may also be used.

【讨论】:

    【解决方案2】:

    完全没有区别。请参阅 Python 文档中Formatted string literals 的定义。

    格式化字符串字面量f-string是以'f'或'F'为前缀的字符串字面量。

    没有进一步提及用于引入文字的特定字符。

    【讨论】:

      【解决方案3】:

      两者没有区别。为了更好地理解,您可以通过字符串格式化。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-29
        • 2020-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-30
        • 1970-01-01
        相关资源
        最近更新 更多