How to format strings in Python

Answered
Jan 05, 2026 1403 views 1 answers
28

What are the different ways to format strings in Python?

D
Asked by devops_guru
Gold 290 rep

1 Answer

14
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
O
Answered by omar_linux 1 week, 2 days ago
Platinum 593 rep

Your Answer

You need to be logged in to answer questions.

Log In to Answer

Related Questions

Hot Questions

No hot questions available.