Python str.format()
Method
The str.format()
method in Python lets you insert values into a string using curly braces {}
as placeholders. It’s a powerful and flexible way to build dynamic strings.
Syntax
"string with {} placeholders".format(values...)
Parameters:
values...
– One or more values to be inserted into the string in the order of the placeholders.
Returns:
- A new string with the placeholders replaced by the provided values.
Example 1: Basic Usage
name = "Alice"
message = "Hello, {}!".format(name)
print(message)
Hello, Alice!
Example 2: Multiple Placeholders
name = "Bob"
age = 30
intro = "My name is {} and I am {} years old.".format(name, age)
print(intro)
My name is Bob and I am 30 years old.
Example 3: Using Index Numbers
sentence = "The {1} is {0} years old.".format(10, "car")
print(sentence)
The car is 10 years old.
Why? The numbers inside {}
refer to the index of values passed into format()
.
Example 4: Named Placeholders
info = "Name: {name}, Age: {age}".format(name="Charlie", age=25)
print(info)
Name: Charlie, Age: 25
Example 5: Formatting Numbers
price = 49.99
text = "Price: ${:.2f}".format(price)
print(text)
Price: $49.99
Why? :.2f
formats the float to 2 decimal places.
Common Use Cases
- Displaying user data in templates or messages
- Logging or outputting debug information
- Formatting numbers, dates, or currency
Common Mistakes
- Mismatch between number of placeholders and arguments
- Using incompatible types (e.g., formatting a list without converting)
Interview Tip
In coding interviews, use str.format()
when building readable strings, especially in questions involving string construction or reporting.
Summary
str.format()
lets you insert variables into strings using{}
- You can use automatic order, index numbers, or named placeholders
- You can apply formatting inside the placeholders
Practice Problem
Write a program that takes a name and score from the user and prints a sentence using str.format()
:
name = input("Enter your name: ")
score = input("Enter your score: ")
print("Hello, {}. You scored {} points.".format(name, score))