28
What are the different ways to format strings in Python?
Loading...
Q&A · Answered
What are the different ways to format strings in Python?
Accepted answer
name = "John"
age = 30
# f-strings (Python 3.6+, recommended)
message = f"Hello, {name}. You are {age}."
# format() method
message = "Hello, {}. You are {}.".format(name, age)
# Named placeholders
message = "Hello, {name}. You are {age}.".format(name=name, age=age)
# % formatting (older style)
message = "Hello, %s. You are %d." % (name, age)
# Format numbers
price = 123.456
formatted = f"${price:.2f}" # $123.46Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.