Python provides several ways to format strings, allowing you to insert variables and control the output format.
1. % Operator: Uses placeholders like %s for strings, %d for integers.
name = “Alice”
age = 30
formatted = “Name: %s, Age: %d” % (name, age)
2. str.format() Method: Uses curly braces {} as placeholders.
formatted = “Name: {}, Age: {}”.format(name, age)
3. F-strings (Python 3.6+): Embeds expressions inside curly braces prefixed by f.
formatted = f”Name: {name}, Age: {age}”
4. Template Strings: Offers simple substitutions, used with string.Template.
from string import Template
template = Template(“Name: $name, Age: $age”)
formatted = template.substitute(name=name, age=age)
Each method offers flexibility depending on the use case, with f-strings being the most concise and readable.