- Home
- /
- Python Format Strings
Python Tutorial
Introduction
Python Data Types & Oper...
Python Strings
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Conditional Statements
Python Loops
Python Functions
Python Modules
Python OOPS
Advanced Topics
File Handling
- Home
- /
- Python Format Strings
Python Format Strings
In Python, it’s common to combine text with values such as names, numbers, or results. This is where formatting strings becomes useful.
Let’s break down how it works and why it’s important.
Combining Strings with Other Strings
The simplest way to combine multiple strings is by using the +
operator. This is called string concatenation.
first_name = "Sarah"
last_name = "Khan"
full_name = first_name + " " + last_name
print(full_name)
Output:
Sarah Khan
Here, two strings are joined with a space in between.
Problem with Concatenating Strings and Numbers
Now let’s say you try to join a string and a number directly:
name = "Ali"
age = 22
print("My name is " + name + " and I am " + age + " years old.")
This will raise an error:
TypeError: can only concatenate str (not "int") to str
Python won’t automatically convert an integer to a string during concatenation. So we need a better way.
The format() Method
The format()
method is used to safely insert values into a string, without worrying about the data type.
student = "Areeba"
score = 87
result = "Student {} scored {} marks in the test.".format(student, score)
print(result)
Output:
Student Areeba scored 87 marks in the test.
The curly brackets {}
are placeholders. Each placeholder is filled with the values provided inside .format()
in the same order.
Using Index Numbers in Placeholders
You can control the order of the values by using index numbers inside the placeholders.
book = "Python Basics"
price = 450
quantity = 3
summary = "You bought {2} copies of '{0}' for a total of Rs.{1}.".format(book, price, quantity)
print(summary)
Output:
You bought 3 copies of 'Python Basics' for a total of Rs.450.
Here, {2}
refers to quantity
, {0}
refers to book
, and {1}
refers to price
. This is useful when you want to rearrange values or reuse the same variable in different positions.
Summary
Use
+
to join only strings.Don’t try to directly combine strings with numbers — it causes an error.
The
format()
method helps combine strings with numbers, variables, or other data safely.You can also control the position of values using index numbers in
{}
.
The format()
method gives you clear control and prevents type-related mistakes when creating dynamic messages in Python.