How to put string parameters in functions inside f strings?

Viewed 794

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?

3 Answers

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. '''...'''

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.

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

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