如何将字符串参数放入 f 字符串内的函数中?

Yoz*_*cks 5 python f-string

我有以下 f 字符串:

f"Something{function(parameter)}"
Run Code Online (Sandbox Code Playgroud)

我想对该参数进行硬编码,它是一个字符串:

f"Something{function("foobar")}"
Run Code Online (Sandbox Code Playgroud)

它给了我这个错误:

SyntaxError: f-string: unmatched '('
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

che*_*ner 7

由于 f 字符串是由词法分析器而不是解析器识别的,因此您不能在字符串中嵌套相同类型的引号。词法分析器只是寻找下一个",而不考虑它的上下文。在内部使用单引号f"..."或在内部使用双引号f'...'

f"Something{function('foobar')}"
f'Something{function("foobar")}'
Run Code Online (Sandbox Code Playgroud)

转义引号不是一个选项(出于目前我无法理解的原因),这意味着任意嵌套的表达式不是一个选项。您只有 4 种类型的报价可供使用:

  1. "..."
  2. '...'
  3. """..."""
  4. '''...'''