How to format a string in Python
Use an f-string: f\"Hello {name}, you have {count} messages\" formats values directly.
from pathlib import Path\nname = \"Alice\"\ncount = 5\nmsg = f\"Hello {name}, you have {count} messages\"\nprint(msg)The snippet defines two example variables, builds a new string with an f-string, and prints it. The f-string evaluates the expressions inside {} at runtime, inserting their values directly into the literal. This syntax is part of Python 3.6+ and is the most concise way to embed variables, arithmetic, or function calls without separate concatenation.
f-strings are faster than str.format() because the formatting is compiled into the bytecode. They keep the template next to the data, improving readability and reducing the chance of mismatched placeholders.
A common gotcha is that braces are used for expression delimiters; to include a literal '{' or '}' you must double them (e.g. f\"{{value}}\"). Also avoid using backslashes inside the expression part, as they are not allowed.
Variations
Using str.format()
template = 'Hello {0}, you have {1} messages'\nmsg = template.format(name, count)\nprint(msg)Works in all Python versions, but more verbose than f-strings.
Safe templating with string.Template
from string import Template\ntmpl = Template('Hello $name, you have $count messages')\nmsg = tmpl.substitute(name=name, count=count)\nprint(msg)Avoids code execution if template comes from untrusted source.
Joining multiple values
parts = [f'Item {i}' for i in range(3)]\nmsg = ', '.join(parts)\nprint(msg)Use ', '.join' for efficient concatenation of many strings.
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.