python backslash in f string code example

Example 1: python f string

>>> name = "Eric"
>>> age = 74
>>> f"Hello, {name}. You are {age}."
'Hello, Eric. You are 74.'

Example 2: 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 assinging '\n' to a name and then .join on that inside the f-string; that is, without using a literal:
Example:
names = ['Adam', 'Bob', 'Cyril']
nl = '\n'
text = f"Winners are:{nl}{nl.join(names)}"
print(text)

Tags:

Java Example