pythonpython-3.xnewlinef-string

How can I use newline '\n' in an f-string to format a list of strings?


I tried this code:

names = ['Adam', 'Bob', 'Cyril']
text = f"Winners are:\n{'\n'.join(names)}"
print(text)

However, '\' cannot be used inside the {...} expression portions of an f-string. How can I make it work? The result should be:

Winners are:
Adam
Bob
Cyril

See Why isn't it possible to use backslashes inside the braces of f-strings? How can I work around the problem? for some additional discussion of why the limitation exists.


Solution

  • Python 3.12+

    You can use backslashes within f-strings and the existing code from the question works as expected. See https://docs.python.org/3.12/whatsnew/3.12.html#pep-701-syntactic-formalization-of-f-strings.

    Python < 3.12

    You can't. Backslashes cannot appear inside the curly braces {}; doing so results in a SyntaxError:

    >>> f'{\}'
    SyntaxError: f-string expression part cannot include a backslash
    

    This is specified in the PEP for f-strings:

    Backslashes may not appear inside the expression portions of f-strings, [...]

    One option is assigning '\n' to a name and then .join on that inside the f-string; that is, without using a literal:

    names = ['Adam', 'Bob', 'Cyril']
    nl = '\n'
    text = f"Winners are:{nl}{nl.join(names)}"
    print(text)
    

    Results in:

    Winners are:
    Adam
    Bob
    Cyril
    

    Another option, as specified by @wim, is to use chr(10) to get \n returned and then join there. f"Winners are:\n{chr(10).join(names)}"

    Yet another, of course, is to '\n'.join beforehand and then add the name accordingly:

    n = "\n".join(names)
    text = f"Winners are:\n{n}"
    

    which results in the same output.

    Note:

    This is one of the small differences between f-strings and str.format. In the latter, you can always use punctuation granted that a corresponding wacky dict is unpacked that contains those keys:

    >>> "{\\} {*}".format(**{"\\": 'Hello', "*": 'World!'})
    "Hello World!"
    

    (Please don't do this.)

    In the former, punctuation isn't allowed because you can't have identifiers that use them.


    Aside: I would definitely opt for print or format, as the other answers suggest as an alternative. The options I've given only apply if you must for some reason use f-strings.

    Just because something is new, doesn't mean you should try and do everything with it ;-)