Python String Formatting


Python provides several ways to format strings — combining text with variables or data, while keeping the output readable and clean.


🔹 The format() Method

You can insert variables into strings using {} placeholders and .format().

name = "Alice"
age = 25

print("My name is {} and I am {} years old.".format(name, age))

✅ Output: My name is Alice and I am 25 years old.


🔹 Positional and Keyword Arguments

You can specify the order using numbers or names.

print("Hello {0}, your score is {1}".format("Bob", 90))
print("Name: {n}, Age: {a}".format(n="Sara", a=22))

🔹 f-Strings (Python 3.6+)

The cleanest and fastest way to format strings in modern Python.

name = "John"
score = 95

print(f"Hello {name}, your score is {score}")

✅ Output: Hello John, your score is 95


🔹 Formatting Numbers

You can format numbers (decimals, padding, etc.) using format specifiers.

pi = 3.14159
print("Value of pi: {:.2f}".format(pi))  # 2 decimal places
num = 5
print(f"{num:03}")  # Pads with zeros: 005

🔹 Aligning Strings

You can align strings using :<, :>, and :^.

txt = "Hello"
print(f"{txt:<10}")  # Left align
print(f"{txt:>10}")  # Right align
print(f"{txt:^10}")  # Center align

🔹 Escape Braces

To print curly braces {}, use double braces {{ and }}.

print("This is a {{bracket}}")

Practice Questions

Q1. Write a Python program to print "Hello, my name is Alice" using the .format() method.

Q2. Write a Python program to use keyword arguments with .format() to insert a name and age into a sentence.

Q3. Write a Python program to display the number 3.4567 rounded as 3.46 using string formatting.

Q4. Write a Python program to print 007 using string formatting to keep leading zeros.

Q5. Write a Python program to use an f-string to show a total score stored in a variable.

Q6. Write a Python program to print a centered title using the ^ alignment symbol in string formatting.

Q7. Write a Python program to format a table with aligned text and numeric values using formatting specifiers.

Q8. Write a Python program to escape curly braces in a string and display {Hello}.

Q9. Write a Python program to combine a string and an integer using string formatting.

Q10. Write a Python program to format a price to 2 decimal places and prefix it with a $ symbol.


Go Back Top