String Formatting in Python
Python provides multiple ways to format strings efficiently. Below are different string formatting techniques with examples.
1. f-strings (Formatted String Literals) – Best & Fastest
Section titled “1. f-strings (Formatted String Literals) – Best & Fastest”Introduced in Python 3.6, f-strings allow embedding expressions inside {} directly within a string.
name = "Gaurav"age = 22print(f"My name is {name} and I am {age} years old.")Output:
My name is Gaurav and I am 22 years old.✅ Supports expressions inside {}
✅ Fastest method
✅ Readable & concise
(a) Evaluating Expressions inside f-strings
Section titled “(a) Evaluating Expressions inside f-strings”num1, num2 = 10, 5print(f"Sum: {num1 + num2}") # Sum: 15(b) Using Functions inside f-strings
Section titled “(b) Using Functions inside f-strings”def square(x): return x * x
print(f"Square of 4 is {square(4)}") # Square of 4 is 16(c) Formatting Numbers using f-strings
Section titled “(c) Formatting Numbers using f-strings”pi = 3.1415926535print(f"Pi rounded: {pi:.2f}") # Pi rounded: 3.14print(f"Formatted number: {1000000:,}") # 1,000,0002. .format() Method – Versatile but Verbose
Section titled “2. .format() Method – Versatile but Verbose”The .format() method allows positional and named placeholders.
name = "Gaurav"age = 22print("My name is {} and I am {} years old.".format(name, age))(a) Positional & Named Placeholders
Section titled “(a) Positional & Named Placeholders”print("Hello, {0}. You are {1} years old.".format("Gaurav", 22))print("Hello, {name}. You are {age} years old.".format(name="Gaurav", age=22))(b) Number Formatting in .format()
Section titled “(b) Number Formatting in .format()”pi = 3.1415926535print("Pi: {:.2f}".format(pi)) # Pi: 3.143. % Formatting (Old Style, Similar to C)
Section titled “3. % Formatting (Old Style, Similar to C)”Older method, less readable but works in all Python versions.
name = "Gaurav"age = 22print("My name is %s and I am %d years old." % (name, age))(a) Formatting Numbers with %
Section titled “(a) Formatting Numbers with %”pi = 3.1415926535print("Pi: %.2f" % pi) # Pi: 3.144. Raw Strings (r"") – Avoiding Escape Sequences
Section titled “4. Raw Strings (r"") – Avoiding Escape Sequences”Raw strings treat backslashes (\) as literal characters.
# Without raw stringprint("C:\new\folder") # Incorrect: \n is treated as a newline
# Using raw stringprint(r"C:\new\folder") # Correct output5. Multi-line Strings (''' or """)
Section titled “5. Multi-line Strings (''' or """)”Used for large text blocks.
text = """This isa multi-linestring."""print(text)6. Escape Characters
Section titled “6. Escape Characters”print("Newline:\nNext line") # \n - Newlineprint("Tab:\tSpace") # \t - Tab spaceprint("Backslash: \\") # \\ - Backslashprint("Quotes: \"Double\" 'Single'") # \" and \' for quotes7. Aligning and Padding Text
Section titled “7. Aligning and Padding Text”name = "Gaurav"print(f"Left: |{name:<10}|") # Left alignprint(f"Right: |{name:>10}|") # Right alignprint(f"Center:|{name:^10}|") # Center align8. Formatting Dates & Times in Strings
Section titled “8. Formatting Dates & Times in Strings”from datetime import datetimenow = datetime.now()print(f"Today: {now:%Y-%m-%d}, Time: {now:%H:%M:%S}")Conclusion
Section titled “Conclusion”| Method | Python Version | Features | Speed |
|---|---|---|---|
| f-strings | 3.6+ | Fastest, cleanest, supports expressions | ⭐⭐⭐⭐⭐ |
.format() | 2.7+ | Flexible but verbose | ⭐⭐⭐ |
% formatting | All | C-style, outdated | ⭐⭐ |
✅ Use f-strings (f"...") whenever possible! 🚀