Search code examples
interpolationpython-3.7f-string

Interpolation of a str.join() via f-string


Attempting to interpolate a str.join() operation:

>>> a = ["a", "b"]
>>> " ".join(a)
'a b'
>>> str = f"data -> {" ".join(a)}"
  File "<stdin>", line 1
SyntaxError: f-string: expecting '}'

f-String does not allow interpolation of such operations?


Solution

  • There is nothing stopping you from using f-interpolation on the join method.

    What is happening here is that you are ending your string with the second ". That causes syntax errors because only one { is present in your f-string. Use triple quotation marks or the single quotation so that the quote character can be included in your string.

    >>> f"""data -> {" ".join(a)}"""
    'data -> a b'
    
    >>> f'data -> {" ".join(a)}'
    'data -> a b'