• Ctrl+C+Python
  • Posts
  • 🐍 Formatting Strings in Python: A Complete Guide

🐍 Formatting Strings in Python: A Complete Guide

When working with Python, formatting strings efficiently can make your code more readable, maintainable, and professional. Python offers multiple ways to format strings, from the traditional % operator to f-strings introduced in Python 3.6. Let's explore the best methods to format strings in Python!

Take your learning to the next level with quick, aesthetic coding tutorials on my YouTube channel! πŸš€βœ¨

πŸŽ₯ Watch now: @CtrlCPython

Subscribe for bite-sized Python lessons with lofi vibes & clean code. β˜•πŸŽΆ 

1. The % Operator (Older Method)

Before Python 3.6, developers often used the % operator for string formatting:

Output:

My name is Alice and I am 25 years old.

While this method works, it is generally outdated and less readable than newer approaches.

2. The .format() Method

Python 3 introduced the .format() method, which is more flexible than % formatting:

Output:

My name is Bob and I am 30 years old.

Positional and Keyword Arguments

You can use positional indexes or keyword arguments for better clarity:

Introduced in Python 3.6, f-strings (formatted string literals) offer the cleanest syntax and best performance:

Output:

My name is Eve and I am 22 years old.

Expressions Inside F-Strings

You can include expressions directly inside f-strings:

Output:

The sum of 10 and 20 is 30.

4. Controlling Decimal Places in Numbers

You can format numbers and control decimal places:

Output:

Pi to 3 decimal places: 3.142

5. Aligning and Padding Strings

F-strings allow easy text alignment using <, >, and ^:

Output:

|Left      |  Center  |     Right|

πŸ† Conclusion

F-strings f"...") are the most efficient and recommended way to format strings in Python due to their simplicity and speed. However, older methods like .format() and % still exist in legacy codebases. Mastering string formatting will help you write cleaner and more professional Python code! πŸš€

Want to learn more? Try experimenting with different string formatting techniques and see how they work in your projects!

What’s your favorite way to format strings in Python? Let me know in the comments! β¬‡οΈπŸ

Happy coding! πŸš€πŸ

Digital Shade

Want more Python tips and tricks?

πŸ”” Join my Beehiiv newsletter for exclusive cheat sheets, Python hacks, and expert tutorials!

Reply

or to participate.