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

问题描述 投票:0回答:2

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

f'This is the value I want quoted: \'{value}\''

这可行,但我想知道是否有一个格式化选项可以为我做到这一点,类似于

%q
在 Go 中的工作方式。基本上,我正在寻找这样的东西:

f'This is the value I want quoted: {value:q}'
>>> This is the value I want quoted: 'value'

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

python string-formatting
2个回答
5
投票

使用 显式转换标志

!r
:

>>> value = 'foo'
>>> f'This is the value I want quoted: {value!r}'
"This is the value I want quoted: 'foo'"

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

由于 PEP 3101 中未记录的某种原因,还有一个

!a
标志,可以使用
ascii
进行转换:

>>> f'quote {"🔥"!a}'
"quote '\\U0001f525'"

还有一个

!s
代表
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>'

0
投票

另一种方法可能只是字符串格式化,例如:

string ="Hello, this is a '%s', '%d' is a decimal, '%f' is a float"%("string", 3, 5.5)
print(string)

这将返回:

Hello, this is a 'string', '3' is a decimal, '5.500000' is a float
© www.soinside.com 2019 - 2024. All rights reserved.