Python String Formatting

String formatting allows you to insert variables and values into a string. This is useful when you want to combine text and variables in a readable way. String Concatenation You can combine strings using the + operator. Example: Output: Using f-Strings An f-string allows you to insert variables directly inside a string. To create an […]

2 mins read Lesson 37 of 48 77% through track

String formatting allows you to insert variables and values into a string.

This is useful when you want to combine text and variables in a readable way.

String Concatenation

You can combine strings using the + operator.

Example:

name = "John"
print("My name is " + name)

Output:

My name is John

Using f-Strings

An f-string allows you to insert variables directly inside a string.

To create an f-string, put the letter f before the string and place variables inside curly braces {}.

Example:

name = "John"
print(f"My name is {name}")

Output:

My name is John

Multiple Variables

You can insert multiple variables into an f-string.

Example:

name = "John"
age = 25

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

Output:

My name is John and I am 25 years old.

Expressions in f-Strings

You can perform calculations inside the curly braces.

Example:

price = 50
quantity = 2

print(f"Total Price: {price * quantity}")

Output:

Total Price: 100

Formatting Numbers

You can format numbers inside f-strings.

Example:

price = 49.999

print(f"Price: {price:.2f}")

Output:

Price: 50.00

The .2f means display the number with 2 decimal places.

Using format()

The format() method is another way to format strings.

Example:

name = "John"

print("My name is {}".format(name))

Output:

My name is John

Multiple Values with format()

Example:

name = "John"
age = 25

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

Output:

My name is John and I am 25 years old

Positional Arguments

You can specify the position of values.

Example:

print("I like {1} and {0}".format("Python", "Django"))

Output:

I like Django and Python

Named Arguments

Example:

print("Name: {name}, Age: {age}".format(name="John", age=25))

Output:

Name: John, Age: 25

Escape Curly Braces

Use double curly braces to display curly braces in output.

Example:

print(f"{{Hello}}")

Output:

{Hello}

Why Use String Formatting?

String formatting helps you:

  • Create dynamic messages
  • Display variables in text
  • Format numbers and values
  • Build user-friendly output

Example:

product = "Laptop"
price = 50000

print(f"The price of {product} is ₹{price}")

Output:

The price of Laptop is ₹50000

Summary

  • String formatting inserts values into strings.
  • f-strings are the preferred and easiest method.
  • Variables are placed inside {}.
  • Expressions can be used inside f-strings.
  • The format() method is another formatting option.
  • Numbers can be formatted using specifiers like .2f.