0
0
PythonHow-ToBeginner · 3 min read

How to Format Strings in Python: Syntax and Examples

In Python, you can format strings using f-strings by placing expressions inside curly braces within a string prefixed with f. Alternatively, use the format() method or the older % operator to insert values into strings.
📐

Syntax

Python offers three main ways to format strings:

  • f-strings: Use f"text {variable}" to embed expressions directly.
  • format() method: Use "text {}".format(value) to insert values.
  • % operator: Use "text %s" % value as an older style.
python
name = "Alice"
age = 30

# f-string
print(f"Name: {name}, Age: {age}")

# format() method
print("Name: {}, Age: {}".format(name, age))

# % operator
print("Name: %s, Age: %d" % (name, age))
Output
Name: Alice, Age: 30 Name: Alice, Age: 30 Name: Alice, Age: 30
💻

Example

This example shows how to use f-strings to format a greeting message with variables.

python
user = "Bob"
score = 95.5

message = f"Hello, {user}! Your score is {score:.1f}."
print(message)
Output
Hello, Bob! Your score is 95.5.
⚠️

Common Pitfalls

Common mistakes include forgetting the f prefix for f-strings, mixing up curly braces, or using the wrong type specifier.

Also, the % operator is less flexible and can cause errors if types don't match.

python
name = "Eve"

# Wrong: missing f prefix
# print("Hello, {name}!")  # prints literal braces

# Right:
print(f"Hello, {name}!")
Output
Hello, Eve!
📊

Quick Reference

MethodSyntaxDescription
f-stringf"Hello, {name}!"Embed expressions directly, Python 3.6+
format()"Hello, {}".format(name)Insert values using placeholders
% operator"Hello, %s" % nameOld style, less flexible

Key Takeaways

Use f-strings for clear and concise string formatting in Python 3.6 and above.
The format() method works well for inserting multiple values with placeholders.
Avoid the % operator for new code as it is older and less flexible.
Always prefix strings with f when using f-strings to evaluate expressions.
Use type specifiers like :.2f inside braces to format numbers precisely.