What does {:02d} mean in Python?

Format Specifier Feature

String formatting is a very essential element of Python programming. Usually, we get strings that are not completely in the format that we want them to be in. Converting the string in the desired format is called string formatting.

To know more about Python Strings, check out this article.

In this article, we will brush through different ways of string formatting and how {:02d} is related and used in string formatting.

Introduction to Python

Python is a very user-friendly language with very easy-to-learn and grasp syntax, it is gaining popularity due to its English-like syntax and endless libraries.

Python has different data types, viz. integers, booleans, strings, and so on. Python has a great mechanism to handle strings and format them, which we will be discussing in detail in further sections.

To understand Python programming in detail, check out the linked article.

Need of String Formatting in Python

Python has great features for string formatting and manipulation. String plays a vital role in a program or project as Python takes input in the form of strings only, and the input is not always ready to be used for processing. Being careless with strings can lead to errors and may even break our code, so it is important to handle strings, convert them to the desired format, and then pass them on to the processing part.

A well-formatted string is always more readable than the unformatted one.

Understanding String Formatting

Let’s understand the process of string formatting in a bit more detail:

Different Formatting Method

Python provides various methods by which we can have strings in the format that we want them to be in. Some of the methods are shown below:

‘%’ Formatting

To use this method, we should start by knowing about the format specifier. Format specifiers are nothing but characters or alphabets that are written along with the ‘%’ sign to identify the data type.

They are as follows: %s is used for strings, %d for decimals or integers, %f for floats, and various others. To see how this works, we shall directly jump to an example:

city = "Pune"
day = 2

message = "I moved to %s %d days ago." %(city, day)

print(message)

The above code will insert the variable values in the order of the access specifier in which they appear in the string. The output can be seen as shown below:

String Format Type1
String Formatting Type1

This method of string formatting is one of the older methods.

Formatted String Literals

In this method, we will the fstrings, which are nothing but formatted strings.

To implement this, we need to start by writing ‘f’ at the beginning of the string before the quotations and mentioning the formatting variables where we want them to be placed inside a set of curly braces ‘{}’.

Let’s jump to an example for a better understanding:

city = "Pune"
day = 2

message = f'I moved to {city} {day} days ago.'

print(message)

The above code will give the following output:

String Format Type2
String Formatting Type2

‘str.format()’

This method requires placing empty curly braces as placeholders for the formatting variables, and then towards the end, we need to finish with a ‘.format()’ function, in which we mention the formatting variable in the order in which we want to place them inside the string.

name = "George"

marks = '85'

subject = 'Maths'

message = "{} got {} marks in {}.".format(name, marks, subject)

print(message)

Output for the above code is as given below:

String Format Type3
String Formatting Type3

Advantages of using Format Specification

The format specification is very helpful in terms of presenting your data, and you can format it in your desired style and present it to people who might be able to understand the data better.

Formatting specification makes the code easier to read and maintain which further boosts productivity by many folds as the efficiency increases. Consistency of data increases as the data flows through the program in a specified format.

The ‘{:02d}’ Format Specification

Understanding the various parts of ‘{:02d}’

Importance of colon(:) in the format specification

The colon(:) is really important as it is used as a differentiator or a dividing wall between the placeholders and the format specifiers.

Controls the precision of data flow and displays output. It improves consistency and efficiency and makes controlling the presentation of data much easier.

Why do we need ‘0’?

The zero makes sure that zero-padding is added to the number.

In this context, consider a case where we have a number in which the digits are less than 2, to make sure that the width of the number is consistent, it will add zeros to fill the remaining space so that the number of digits becomes equal to 2.

Why do we need ‘2’?

Resemble the width of the formatted number or integer. The resulting string must have at least these many digits in it; if it exceeds the limit, then the digits are adjusted to fit within the specified width.

Why do we need ‘d’?

‘d’ is nothing but a format specifier, as we have seen in one of the above sections. It just shows that this place is occupied by an integer.

Let’s see an example of {:02d}:

n1 = 1
n2 = 23
n3 = 456

n1 = "{:02d}".format(n1)
n2 = "{:02d}".format(n2)
n3 = "{:02d}".format(n3)

print(n1)
print(n2)
print(n3)
Format Specification Example
Format Specification Example

Zero Padding

What is Zero Padding?

Python doesn’t support integers will leading zeros. In such case, if you want to add zeros, the method that you will use is ‘Zero Padding’. Zero padding simply adds leading zeros to a number so that it occupies the width that is passed.

As we have seen in the above example, {:02d} adds one leading zero to all the single-digit numbers so that the width of the number is equal to 2. This addition of leading zero to meet the required width is called ‘Zero Padding’.

Example of ‘Zero Padding’

In the context of {:02d}, we will see how zero padding works on both single and multi-digit integers.

#Single Digit

n1 = 9
n2 = 8
n3 = 3

#Multi Digit

n4 = 12
n5 = 345
n6 = 6789

###Formatting

#SINGLE
n1 = "{:02d}".format(n1)
n2 = "{:02d}".format(n2)
n3 = "{:02d}".format(n3)

#MULTI

n4 = "{:02d}".format(n4)
n5 = "{:02d}".format(n5)
n6 = "{:02d}".format(n6)

print("Single Digit Format:")
print(n1)
print(n2)
print(n3)

print("Multi-digit Format:")
print(n4)
print(n5)
print(n6)

You can see the difference between single and multi-digit integers in the output as shown in the below image:

Zero Padding Example
Zero Padding Example

Practical Applications

After studying the theory concepts, it’s now time to understand and take a look at how we can use the above-gained knowledge in practical applications.

Some examples are given below:

Date Time Formatting

The {:02d} can be used with other format specifiers to format the date in the desired format.
We will be formatting the date in the format DD/MM/YYYY format with the help of the format specifiers in the below example:

from datetime import datetime as dt

date = dt(2023, 7, 26)

year = date.year
month = date.month
day = date.day

#Get date in DD/MM/YYYY format
new_date_format = "{:02d}/{:02d}/{:04d}".format(day, month, year)

print("Default Format of Date: ",date)

print("New format of date: ",new_date_format)

If the above code is without any errors, it should give this output. You can see how the format specifier helps us in formatting strings very easily.

Date Time Example
Date Time Example

Generating Sequence of Filenames

We are working on projects that require you to handle a large number of files with the same path and almost the same name, you might have to manually create a list of these, but using a format specifier, we can automate this boring process.

Let us understand this process with a simple example.

## Generating filenames

number_of_files = 5
prefix = 'sample'
extension = '.doc'

filenames = ["{}{:02d}{}".format(prefix, i, extension) for i in range(1, number_of_files+1)]

for file in filenames:
	print(file)

Running the above code will generate a list of filenames as specified in the parameter, which can be seen in the image below:

Filname Generating Example
Filename Generating Example

Best Practices and Tips

Common Mistakes To Avoid

People commit common mistakes while using these format specifiers and then struggle to figure out what’s going wrong in the code, so it is important to avoid making these small mistakes.

These could be a missing or misplaced colon (:), maybe omitting the width specifier, or maybe mismatched format specifiers.

To avoid these mistakes, it is strongly recommended to adhere to the syntax and the way of writing that is mentioned in the article above.

Formatting Negative Integers

To use the format specifier for negative integers, we would need to use the ‘abs()’ method in the earlier versions, but now we can handle the negative integers in the same way as we did with the positive ones.

Summary

In conclusion, let’s brush through all the concepts that we went through the in this article. We started by understanding Python and its String, and how string formatting is important.

We covered various string formatting methods and techniques and even saw examples of them. We did a proper autopsy of the {:02d} format specifier to understand how it works and what is the relevance of each of its components.

Towards the end, we figured out what zero padding is and, after that, saw some practical applications.

To conclude, there are some best practices and tips mentioned to be followed while using {:02d}.

References

Official Documentation

Stackoverflow Query