classification
Title: Use the same kind of quotation mark in f-string
Type: enhancement Stage: resolved
Components: Library (Lib) Versions: Python 3.10
process
Status: closed Resolution: duplicate
Dependencies: Superseder:
Assigned To: Nosy List: Nghia Minh, eric.smith, steven.daprano
Priority: normal Keywords:

Created on 2020-07-08 09:08 by Nghia Minh, last changed 2020-07-08 10:47 by steven.daprano. This issue is now closed.

Messages (3)
msg373296 - (view) Author: Nghia Minh (Nghia Minh) Date: 2020-07-08 09:08
I want to use the same type of quotation mark in f-string, like this:

f'Hey, {' this quote is wrong.'}'

Currently we have to:

f'But, {" this quote is right."}'
msg373297 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2020-07-08 09:13
This is a limitation of the parser: the entire f-string is first evaluated as a string.

Just as 
'Hey, {' this quote is wrong.'}'
or
r'Hey, {' this quote is wrong.'}'
are not valid strings, neither is
f'Hey, {' this quote is wrong.'}'

See issue 33754 for a possible future change that would address this.
msg373305 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2020-07-08 10:47
Just change the f string quotes.

Python strings, whether f-strings or not, can be delimited by '' or "" or triple quotes. So this works:


>>> f"But, {'this quote is right.'}"
'But, this quote is right.'

Remember that the part of the f-string is evaluated as code, converted to a string, and interpolated into the rest of the f-string body. This is why the quotes disappear.

If you need both kinds of quotes, use triple-quotes as the delimiter:

>>> f"""Both {'single and "double" quotes'.title()}"""
'Both Single And "Double" Quotes'

I assume you want to pass the '' string to a function or something, and this example is just a simplified version. Because if there is no function call needed, you should just use a regular string, there's no need for an f-string:

"But, 'this quote is right.'"
History
Date User Action Args
2020-07-08 10:47:59steven.dapranosetnosy: + steven.daprano
messages: + msg373305
2020-07-08 09:13:03eric.smithsetstatus: open -> closed

nosy: + eric.smith
messages: + msg373297

resolution: duplicate
stage: resolved
2020-07-08 09:08:25Nghia Minhcreate