String Formatting in Python

 

 

What is String Formatting?

String formatting allows us to dynamically insert values into a string. Instead of messy concatenation (+), we can format strings elegantly and efficiently. Think of it as painting a masterpiece, but with text!

Why Use String Formatting?

  • Readable and clean code! 
  • Avoid errors when mixing data types! 
  • Dynamic text generation! 

Using f-strings (Best & Modern Way)

name = "Alice"
age = 25
print(f"Hello, my name is {name} and I am {age} years old.")
# Outputs: Hello, my name is Alice and I am 25 years old.

Formatting Numbers

pi = 3.14159
print(f"Pi rounded to 2 decimal places: {pi:.2f}")  # Outputs: Pi rounded to 2 decimal places: 3.14

Using Expressions Inside {}

print(f"Next year, I will be {age + 1} years old!")  # Outputs: Next year, I will be 26 years old!

Using .format() (Older but Still Useful)

print("Hello, my name is {} and I am {} years old.".format(name, age))
# Outputs: Hello, my name is Alice and I am 25 years old.

Named Placeholders

print("{greeting}, my name is {person}!".format(greeting="Hi", person=name))
# Outputs: Hi, my name is Alice!

Using % Formatting (Old School)

print("My age is %d years." % age)  # Outputs: My age is 25 years.
print("Pi is approximately %.2f" % pi)  # Outputs: Pi is approximately 3.14

This method is outdated and not recommended for new projects.

Summary 

Method Description
f-strings (f"...") Modern, fast, and best for readability
.format() Versatile and supports named placeholders
% formatting Old-school method, not recommended


Post a Comment

0 Comments