Master string formatting in Python-P1-Legacy Formatting

Published On: Wed, 23 Oct 2024 Updated On: Wed, 23 Oct 2024

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.

  1. 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."
  2. 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.

Code Example
print("Hello, %s! You are %d years old." % ("John", 30))

Challenges

This method had several challenges mentioned below:

  1. It is less readable and error-prone for complex formatting.
  2. It is less flexible and has no support for keyword arguments or nested formatting.
  3. 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?

  1. Use wisely in simple cases where readability is not important.
  2. Maintain legacy code or keep your Python code compatible with older versions.
While %-formatting is still available, I recommend newer formatting methods for better readability, flexibility and future-proofing your code.

Alternatives

  • str.format() (Python 2.6+) - We will dive deep to discuss this method in the next part of the article.
Code Example
print("Hello, {}! You are {} years old.".format(name, age))
  • f-strings (Python 3.6+) - Known as Formatted String Literals
Code Example
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.

Code Example
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:

Code Example
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

  1. What is the purpose of the %s format specifier?
  2. How do you left-justify a string?
  3. What is the difference between %f and %g format specifiers?
  4. How do you format an integer as a hexadecimal value?
  5. What is the purpose of the # modifier?
  6. 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