5

I have the following f-string:

f"Something{function(parameter)}"

I want to hardcode that parameter, which is a string:

f"Something{function("foobar")}"

It gives me this error:

SyntaxError: f-string: unmatched '('

How do I do this?

1
  • 2
    You can use second type of quote character which is f"Something{function('foobar')}" Commented Dec 20, 2021 at 21:22

3 Answers 3

7

Because f-strings are recognized by the lexer, not the parser, you cannot nest quotes of the same type in a string. The lexer is just looking for the next ", regardless of its context. Use single quotes inside f"..." or double quotes inside f'...'.

f"Something{function('foobar')}"
f'Something{function("foobar")}'

Escaping quotes is not an option (for reasons that escape me at the moment), which means arbitrarily nested expressions are not an option. You only have 4 types of quotes to work with:

  1. "..."
  2. '...'
  3. """..."""
  4. '''...'''
Sign up to request clarification or add additional context in comments.

1 Comment

"Escaping quotes is not an option" - I bet language designers did not want to deal with the awkward escaping madness which could happen inside f-string expressions, and decided to keep it simple.
3

You can use the fact that python has two types of quotes:

f"Something{function('foobar')}"

or

f'Something{function("foobar")}'

What you unfortunately can't do, is escape the inner string's quotes. f"Something{str.upper(\"foobar\")}" will result in

SyntaxError: f-string expression part cannot include a backslash

This is specifically addressed in PEP-498, which defines how f-strings work.

Comments

0

Python allows both "" and '' around strings. Easiest is to use:

f"Something{function('foobar')}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.