Search code examples
pythonf-string

How to put string parameters in functions inside f strings?


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?


Solution

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