Master string formatting in Python-P1-Legacy Formatting
Introduction
Python 3.6 introduced a new way of formatting strings known as Formatted String Literals or F-Strings. Python has multiple ways to format the strings the way you want. However, each approach has its advantages and disadvantages. This article is going to be in lengthy parts. Before we start our discussion, I suggest reading other short tutorials If you don't want to participate in this discussion. Those articles will give you knowledge at the surface and several examples that will make you feel you learned it right. Please feel free to check those articles. But if you want to learn real stuff and deep dive into Mastering f-strings in Python, continue reading this. Additionally, I suggest you practice along with me. So without any more discussion, let's start with the question.
What is %-formatting
in Python?
This is the legacy method for formatting strings in Python. It uses a %
sign followed by a format specifier to replace it with the actual value in the asked format. This string formatting method is still supported in the latest version of Python. However, it is a less preferred method than newer formatting approaches.
Syntax
Its syntax contains the below two parts.
- The first part contains the string within quotation marks having
%
symbol followed by a format specifier. For example"Hello, %s! You are %d years old."
- The second part contains the values to be inserted after the first part separating it with the
%
symbol. For example,values1, valuue2,...
See the below example for your reference.
print("Hello, %s! You are %d years old." % ("John", 30))
Challenges
This method had several challenges mentioned below:
- It is less readable and error-prone for complex formatting.
- It is less flexible and has no support for keyword arguments or nested formatting.
- It is marked as deprecated and may be removed in future Python versions.
Then the question might come in your genius brain🤔when should we use it?
- Use wisely in simple cases where readability is not important.
- Maintain legacy code or keep your Python code compatible with older versions.
Alternatives
-
str.format()
(Python 2.6+) - We will dive deep to discuss this method in the next part of the article.
print("Hello, {}! You are {} years old.".format(name, age))
-
f-strings
(Python 3.6+) - Known as Formatted String Literals
print(f"Hello, {name}! You are {age} years old.")
Before moving to these alternative methods, you must understand format specifiers, and modifiers along with how to control the width and precision.
Format Specifiers and Usage
Format Specifier | Replaces |
%s | String |
%d | Decimal integer |
%i | Integer |
%f | Floating-point number |
%e | Exponential notation |
%E | Exponential notation (uppercase) |
%g | General format (float or exponential) |
%G | General format (float or exponential, uppercase) |
%c | Character |
%r | Raw string (repr()) |
%x | Hexadecimal integer (lowercase) |
%X | Hexadecimal integer (uppercase) |
%o | Octal integer |
%p | Pointer (memory address) |
%n | Nothing (suppress output) |
Modifiers and Usage
Modifier | Significance |
* | Argument as width or precision |
- | Left justifies the value |
+ | Force sign |
<space> | Positive Sign |
# | Alternate form (prefix for hex, octal) |
0 | Padd with zeros |
Width And Precision
Example Combination | What does it do? |
%10s | String with minimum width 10 |
%.2f | Float with precision 2 |
%05d | Integer with a minimum width of 5 and padded with zeros |
Now you know what are the format specifiers and modifiers. Try the below code in your machine and experiment with them.
print("Student Table")
print("%s" % ("-"*37))
print("%10s %20s %5s" % ("First Name", "Last Name", "Age"))
print("%10s %20s %5s" % ("Kamal", "Mehta", 40))
Output
More examples:
print("String and Integer: %s %d" % ("Hello", 42))
print("Floating-point number: %f" % 3.14159)
print("Hexadecimal integer: %x" % 255)
print("String with minimum width 10: %10s" % "Hello")
print("Float with precision 2: %.2f" % 3.14159)
print("Integer with forced sign: %+d" % 42)
print("Integer with minimum width 5, padded with zeros: %05d" % 12)
Remember, practice will make you a competitive developer. Experiment with different format specifiers and modifiers to solidify your understanding. Stay tuned for the next part of this article, where we'll dive deeper into str.format()
and f-strings
. Here are some interview questions on format specifiers that will help you crack any Python Development interview.
Interview Questions
- What is the purpose of the
%s
format specifier? - How do you left-justify a string?
- What is the difference between
%f
and%g
format specifiers? - How do you format an integer as a hexadecimal value?
- What is the purpose of the
#
modifier? - How do you control the width and precision of Python string formatting?
Conclusion
We explored the legacy %-formatting method for formatting strings in Python, its syntax, and usage. We discussed its limitations, including readability issues, lack of flexibility, and deprecation. We also introduced alternative formatting methods, such as str.format()
and f-strings
, and emphasized the importance of understanding format specifiers and modifiers. By mastering these concepts, you will be a competitive programmer, proficient in formatting strings in Python using the old %-formatting method and writing more readable and maintainable code. Happy coding!
Continue reading the next part - Master string formatting in Python Part 2 using str.format()
Reader Comments
Add a Comment
Recent Posts
- The Power Of Prompt Engineering | The Power Of Prompt Engineering
- Long-Term Prompting Strategies | The Power Of Prompt Engineering
- Advantages of Using GNU Sed | Enhance Your Text Processing
- An Introduction to Mojo Programming Language
- Guiding the Path to Engagement | Practical Prompt Engineering
- Mastering the Art of Writing Perfect ChatGPT Prompts | A Comprehensive Guide With Examples
- What is Sedition Law in India? | Origins, History, and Implications
- Everything You Need to Know About Encapsulation in Python: A Deep Dive
- Is Python and Django Enough to Conquer the Web Development Realm?
- How to Fix the "No Python Found" Error in Pipenv on Windows: A Comprehensive Guide
- Master string formatting in Python-P2-str.format()
- Master string formatting in Python-P3-f-strings