-
Hajipur, Bihar, 844101
Python provides several ways to format strings — combining text with variables or data, while keeping the output readable and clean.
format()
MethodYou 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.
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))
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
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
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
To print curly braces {}
, use double braces {{
and }}
.
print("This is a {{bracket}}")
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.
Q1: Which method is used to insert variables into a string?
Q2: What do curly braces {} do in a formatted string?
Q3: Which string formatting was introduced in Python 3.6?
Q4: What does {:.2f} format specifier do?
Q5: What is the output of f"{5:03}"?
Q6: How do you align text to the right in format?
Q7: Which is NOT a valid format method?
Q8: How do you insert a literal { in format strings?
Q9: What will "{name}".format(name="Alex") return?
Q10: Which is more efficient for string formatting in Python 3.6+?