英文:
Quote string value in F-string in Python
问题
f'这是我想引用的值:\'{value}\''
f'这是我想引用的值:{value!r}'
你可以选择使用单引号或双引号。
英文:
I'm trying to quote one of the values I send to an f-string in Python:
f'This is the value I want quoted: \'{value}\''
This works, but I wonder if there's a formatting option that does this for me, similar to how %q
works in Go. Basically, I'm looking for something like this:
f'This is the value I want quoted: {value:q}'
>>> This is the value I want quoted: 'value'
I would also be okay with double-quotes. Is this possible?
答案1
得分: 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-strings之前引入的功能)。
出于某种在PEP中未记录的原因,还有一个!a
标志,它使用ascii
进行转换:
>>> f'quote {"\u128293"!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>'
英文:
Use the explicit conversion flag !r
:
>>> value = 'foo'
>>> f'This is the value I want quoted: {value!r}'
"This is the value I want quoted: 'foo'"
The r
stands for repr
; the result of f'{value!r}'
should be equivalent to using f'{repr(value)}'
(it's a feature that predates f-strings).
For some reason undocumented in the PEP, there's also an !a
flag which converts with ascii
:
>>> f'quote {"🔥"!a}'
"quote '\\U0001f525'"
And there's an !s
for str
, which seems useless... unless you know that objects can override their formatter to do something different than object.__format__
does. It provides a way to opt-out of those shenanigans and use __str__
anyway.
>>> 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>'
答案2
得分: 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
英文:
Also another way could be just string formatting as for example:
string ="Hello, this is a '%s', '%d' is a decimal, '%f' is a float"%("string", 3, 5.5)
print(string)
This would return:
Hello, this is a 'string', '3' is a decimal, '5.500000' is a float
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论