在 Python 中的 F 字符串中引用字符串值

Woo*_*193 3 python string-formatting

我试图引用我发送到 Python 中的 f 字符串的值之一:

f'This is the value I want quoted: \'{value}\''
Run Code Online (Sandbox Code Playgroud)

这可行,但我想知道是否有一个格式化选项可以为我执行此操作,类似于%qGo 中的工作方式。基本上,我正在寻找这样的东西:

f'This is the value I want quoted: {value:q}'
>>> This is the value I want quoted: 'value'
Run Code Online (Sandbox Code Playgroud)

我也可以使用双引号。这可能吗?

wim*_*wim 5

使用显式转换标志 !r

>>> value = 'foo'
>>> f'This is the value I want quoted: {value!r}'
"This is the value I want quoted: 'foo'"
Run Code Online (Sandbox Code Playgroud)

代表;rrepr的结果f'{value!r}'应该等同于 using f'{repr(value)}'(这是一个早于 f 字符串的功能)。

由于 PEP 中未记录的某种原因,还有一个!a标志可以转换为ascii

>>> f'quote {""!a}'
"quote '\\U0001f525'"
Run Code Online (Sandbox Code Playgroud)

还有一个!sfor str,它看起来没什么用......除非你知道对象可以覆盖它们的格式化程序来执行与object.__format__实际不同的操作。它提供了一种选择退出这些恶作剧__str__无论如何使用的方法。

>>> class What:
...     def __format__(self, spec):
...         if spec == "fancy":
...             return ""
...         return "potato"
...     def __str__(self):
...         return "spam"
...     def __repr__(self):
...         return "<wacky object at 0xcafef00d>"
... 
>>> obj = What()
>>> f'{obj}'
'potato'
>>> f'{obj:fancy}'
''
>>> f'{obj!s}'
'spam'
>>> f'{obj!r}'
'<wacky object at 0xcafef00d>'
Run Code Online (Sandbox Code Playgroud)

  • 我投了赞成票,但可能值得指出的是,这与字符串上的“repr”相同 (2认同)