String Formatting in Python

String formatting allows us to combine text and variables in a readable and structured way. Python provides multiple methods for formatting strings.

💡 String formatting helps make output cleaner and easier to understand.

Using Comma in print()

The simplest way to format strings is by using commas inside the print() function.

name = "Khushi"
age = 18
print("My name is", name, "and I am", age, "years old")

Using + Operator

Strings can be joined using the + operator. Numbers must be converted to strings before concatenation.

name = "Python"
version = 3
print("I am learning " + name + " " + str(version))
❌ You cannot directly add strings and numbers without conversion

Using format() Method

The format() method allows us to insert variables into placeholders.

name = "Khushi"
marks = 95
print("Student {} scored {} marks".format(name, marks))

Using f-Strings (Recommended)

f-Strings are the most modern and readable way to format strings in Python. They were introduced in Python 3.6.

name = "Khushi"
age = 18
print(f"My name is {name} and I am {age} years old")
✅ f-Strings are fast, clean, and easy to read

Practice

  1. Print your name and age using f-strings
  2. Display the sum of two numbers using format()