Introduction ๐
String formatting allows you to insert variables, values, and expressions inside strings dynamically. It makes your output clean, readable, and professional โ essential for building real-world applications.
Note
1. Why String Formatting? ๐ค
Without formatting, combining strings and variables becomes messy:
without_formatting.py
name = "Sathish"
age = 25
print("My name is " + name + " and I am " + str(age) + " years old.")This is hard to read. Let's fix it with formatting! ๐
2. f-Strings (Best & Recommended) โจ
Introduced in Python 3.6, f-strings allow embedding variables using .
fstring_basic.py
name = "Sathish"
age = 25
print(f"My name is {name} and I am {age} years old.")Use expressions inside f-strings
fstring_expressions.py
print(f"Next year, you will be {age + 1}")Formatting numbers
fstring_numbers.py
price = 49.5678
print(f"Price: {price:.2f}") # 2 decimal placesAlignment with f-strings
fstring_alignment.py
print(f"{'Python':>10}") # right aligned
print(f"{'Python':<10}") # left aligned
print(f"{'Python':^10}") # center alignedNote
3. format() Method ๐งฐ
The format() function allows placeholder-based formatting using .
Basic Usage
format_basic.py
name = "Sathish"
age = 25
print("My name is {} and I am {} years old.".format(name, age))Positional Arguments
format_positional.py
print("I live in {1} and my name is {0}".format("Sathish", "India"))Named Arguments
format_named.py
print("Name: {name}, Age: {age}".format(name="Sathish", age=25))Formatting Numbers
format_numbers.py
print("Value: {:.2f}".format(3.14159))4. % Formatting (Older Style) ๐
This is the oldest Python formatting method, still seen in legacy code.
percent_format.py
name = "Sathish"
age = 25
print("My name is %s and I am %d years old." % (name, age))- %s โ String
- %d โ Integer
- %f โ Float
5. Formatting Dictionaries ๐๏ธ
dict_format.py
person = {"name": "Sathish", "age": 25}
print("Name: {name}, Age: {age}".format(**person))6. Formatting with Padding & Alignment ๐ฏ
padding_alignment.py
print("{:>10}".format("Python")) # right align
print("{:<10}".format("Python")) # left align
print("{:^10}".format("Python")) # center align7. Formatting Numbers (Advanced) ๐ข
Thousands Separator
thousands.py
num = 1234567
print(f"{num:,}") # 1,234,567Percentage Formatting
percentage.py
value = 0.85
print(f"Success rate: {value:.2%}")Scientific Notation
scientific.py
print(f"{1234:e}")8. Combining Strings With Variables ๐งฉ
combine.py
product = "Laptop"
price = 59999
print(f"The {product} costs Rs.{price:,}")9. Real-World Example ๐
real_world_example.py
name = input("Enter your name: ")
score = float(input("Enter your score: "))
print(f"Hello {name}, your score is {score:.2f}!")Conclusion ๐
You have now mastered all key string formatting techniques in Python! Want to continue with Operators, Expressions, Conditional Statements, Loops, Functions, Lists, Tuples, or Dictionaries? Just tell me your next topic! ๐