Skip to content

Q&A · Answered

How to format strings in Python

asked 9 months, 1 week ago 1839 views 1 answer
28

What are the different ways to format strings in Python?

1 Answer

One accepted
14

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago
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.46

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.