1

I have a Python 3.11 script that fails with a syntax error:

values, value = [], "foo" values.append(f"'{string(value).replace('"', '""')}'") 

I don't understand why, please explain.

values.append(f"'{string(value).replace('"', '""')}'") File "<stdin>", line 1 values.append(f"'{string(value).replace('"', '""')}'") ^ SyntaxError: unterminated string literal (detected at line 2) 
4
  • Provide some test data. Commented Jun 9, 2023 at 13:34
  • 1
    Can possibly be simplified to: values.append(str(value).replace('"', '""')), as it appears the f-string is superfluous. Then again, the question in its original (current) state is not reproducible. Commented Jun 9, 2023 at 13:35
  • @LoukasPap It's a syntax error. The value of value is irrelevant. Commented Jun 9, 2023 at 13:38
  • You could use triple quotes (assuming string should be str): values.append(f"""'{str(value).replace('"', '""')}'""") Commented Jun 9, 2023 at 13:49

2 Answers 2

2

Prior to Python 3.12, you cannot nest quotes inside an f-string, even inside a replacement field. The " in the first argument to replace is terminating the f-string literal, meaning the " that you want to terminate the string is actually starting a new string literal.

For now, use f"""...""" to define the literal.


This restriction has been lifted as of (at least) Python 3.12.0.b1 , due to the formalization of f-string literals in the grammar by PEP 701:

Python 3.12.0b1 (main, Jun 4 2023, 16:00:02) [Clang 11.1.0 ] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> string = str >>> value = 9 >>> f"'{string(value).replace('"', '""')}'" "'9'" 
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any benefit from doing string=str or is it just because the asker has it in the code?
That was just to prevent the NameError the literal would otherwise produce.
1

Does values.append(str(value).replace('\"', '\"\"')) work?

You may remove baskclash+double-quote (\") and just keep double quote (") if you want.

4 Comments

You are currently appending a set value to the list.
Why do I append a set value? You mean a set sth like (1,2,..)? I don't understand.
Ohhh I see. Do you mean a dict?
Ohh I didn't know that it creates a set. I corrected it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.