Quote string value in F-string in Python

Question:

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?

Asked By: Woody1193

||

Answers:

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>'
Answered By: wim

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
Answered By: antonioaugello
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.