Master string formatting in Python-P2-str.format()

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

ntroduction

In our previous article, we discussed the legacy method of string formatting in Python i.e. %-formatting. If you have not read it, feel free to go through it as we are going to continue our talk in this article based on the information provided in that article. Don't think too much, you must read it, I have also given format specifiers and modifiers in that chat which will be helpful here. For now, let's continue our discussion for the alternative of the legacy method that was introduced in the Python 2.6 release.

Strings formatting is a crucial aspect of any programming language. It allows developers to create readable and friendly output. Now that you know Python provides several mechanisms to format strings, I must mention that str.format() is one of the preferred methods among the developers that provides benefits such as readability and flexibility. That's what you are going to learn in this discussion thread. So let's get started!

str.format() Method

It's a method that allows you to format strings by replacing placeholders with values. Yes, you heard it right, unlike %-formatting, this mechanism has placeholders that in turn get replaced by the actual values provided as arguments to format() function. Let's see an example so that you can understand it clearly. Below is the basic syntax of str.format().

Code Example
"{} {}".format(value1, value2)

In the above example, {} are the placeholders that will be replaced with value1 and value2. The format() method takes the arguments as input and returns the formatted string.

Positional Arguments

You can also provide the argument positions in the placeholders as given below:

Code Example
"{0} {1}".format(value1, value2)

Isn't it a great feature? Let's tweak it as below.

Code Example
"{1} {0}".format("abc", "def")
# Outout
# 'def abc'

Did you try? Please send the output of the above code in comments.

Named Arguments

You can also use keyword arguments to specify the values to the str.format() method. Let's see the demonstration.

Code Example
"{bird} {color}".format(bird="Sparrow", color="red")
# Output
# 'Sparrow red'

As each value is identified by a keyword, you can use them in any order and it is very convenient compared to the positional parameters to str.format() method. Isn't it? Did you try?

If you have tried it above examples then it's time to move ahead to jump into the use of format specifiers in str.format().

Use of Format Specifiers and Modifiers

Unlike legacy formatting, as we saw in the previous blog, notation is different as we need to use it in the placeholders. This method also allows you to specify the type of the values using type specifiers: 

Type Specifiers

Code Example
"{0:d} {1:f}".format(10, 20.5)
# Output
# '10 20.500000'

In this example, {0:d} will format the value as a decimal integer, and {1:f} will format the value as a floating-point number. Are you ready for some experiment with this? See below.

Code Example
"{0:d} {1:f}".format(10.0, 20)
# Output
# Traceback (most recent call last):
#   File "", line 1, in 
# ValueError: Unknown format code 'd' for object of type 'float'

Let's remove the type specifiers from this example and observe:

Code Example
"{0} {1}".format(10.0, 20)
# Output
# '10.0 20'

What did it do?

Why was it interpreted correctly whereas it gave us an error previously? Any guess?

Implicit Type Conversion - when Python converts the data into desired type itself

Format Specifiers

Format Specifiers allow you to control the formatting of the values as per your requirements. See the below example for clarification.

Code Example
# Type Specifiers
"{0:d} {1:f}".format(10, 20.5)
# Output - '10 20.500000'

# Format Specifiers
"{0:08d} {1:05.2f}".format(10, 20.5)
# Output - '00000010 20.50'

# Formatting Named Placeholders
"{bird:10} {count:+05d}".format(bird="Sparrow", count=10)
# Output - 'Sparrow    +0010'

Here, below are happening:

  1. {0:08d} formats the value as a decimal integer with a minimum width of 8 characters, padding with zeros if necessary.
  2. {1:05.2f} formats the value as a floating-point number with a minimum width of 5 characters and 2 decimal places.
  3. {bird:10} will format the value with a minimum width of 10 characters, and {count:+5d} will format the value as a decimal integer with a minimum width of 5 characters with a + sign padded with 0.

Advanced Usage

We can also perform nested formatting using str.format() method. It allows you to format values inside values. This is useful when you need to format a string that contains another formatted string. Let's see an example of this.

Code Example
def format_float():
    # Supported precisions
    precisions = [".1f", ".2f", ".3f", ".4f", ".5f", ".6f"]

    # Get user input
    num = float(input("Enter a floating point number: "))
    precision = int(input("Enter desired precision (1-6): "))

    # Validate precision
    if precision < 1 or precision > 6:
        print("Invalid precision. Supported precisions are 1-6.")
        return

    # Format string based on precision
    format_spec = precisions[precision - 1]
    formatted_num = "{0:{1}}".format(num, format_spec)

    # Print formatted number
    print("Formatted number: ", formatted_num)

format_float()
Here's how the code works:
  1. The format_float function defines supported precisions up to 6 digits.
  2. It asks the user to enter a floating-point number and the desired precision.
  3. It validates the precision to ensure it's within the supported range (1-6).
  4. It formats the number based on the user-specified precision using the format method.
  5. Finally, it prints the formatted number.

You must try the above example on your machine and let me know your thoughts in the comments below this blog. So let's conclude this thread.

Conclusion

str.format() is a powerful and flexible method for string formatting in Python. Its features, such as positional and keyword arguments, type specifiers, format specifiers, named placeholders, and advanced usage, make it a popular choice among developers. Mastering it allows you to create more readable and user-friendly output in your Python applications.

We have seen the use of str.format() function in detail and how we can use it in various use cases. If you are a developer and working on an existing project, you will be able to understand string formatting better. But this is no end. Python introduced a new mechanism in the 3.6 version which has more readability and flexibility that is somewhat similar to keyword arguments but concise. We will see it in the next part of this String Formatting in Python Series.

Reader Comments


Add a Comment