5 Best Ways to Get a String Left Padded with Zeros in Python

πŸ’‘ Problem Formulation: When working with numeric identifiers, such as account numbers or fixed-size tokens, a common requirement is to ensure they follow a standard length by padding with leading zeros. For instance, converting the integer 42 into the string '00042' when a five-character string is required. This article discusses several methods to achieve left padding of strings with zeros in Python.

Method 1: Using the zfill() Method

The zfill() method in Python pads a string on the left with zeros (‘0’) to reach a specified length. It’s a simple and convenient string method that doesn’t require importing any additional modules.

Here’s an example:

account_number = '42'
print(account_number.zfill(5))

Output:

00042

We took a string '42' and used the zfill() method with the argument 5 to indicate the total length of the resulting string. It automatically added three leading zeros to meet the specified length.

Method 2: Using the rjust() Method

The rjust() method is a string method that right-justifies the original string by padding it with a specified padding character (defaults to space) up to a certain width. To pad with zeros, you can specify ‘0’ as the padding character.

Here’s an example:

order_id = '123'
padded_order_id = order_id.rjust(6, '0')
print(padded_order_id)

Output:

000123

In this snippet, the rjust() method is used to pad '123' with zeros up to 6 characters in total. The second argument ‘0’ indicates that we’re padding with zeros instead of the default whitespace.

Method 3: Using String Formatting with %

String formatting using the % operator allows you to pad a number with zeros using a specific format specifier. It is like the printf-style formatting available in many other programming languages.

Here’s an example:

serial = 7
formatted_serial = '%05d' % serial
print(formatted_serial)

Output:

00007

The % operator is used here with a format specifier '%05d' that instructs Python to format the variable serial into a five character long string, padding with zeros where necessary.

Method 4: Using String Formatting with str.format()

Python’s new-style string formatting method str.format() offers a flexible and readable way to format strings. You can use curly braces and colons to define the padding and alignment specifications.

Here’s an example:

transaction_id = 314
formatted_transaction_id = '{:0>5}'.format(transaction_id)
print(formatted_transaction_id)

Output:

00314

In this example, '{:0>5}' is the format pattern used, where 0 is the padding character, > indicates right alignment (which is equivalent to left padding in this context), and 5 is the total length of the output string.

Bonus One-Liner Method 5: Using f-Strings

Python 3.6 introduced f-strings, a more concise and readable way to format strings. It allows for in-line expression evaluation and formatting specifications.

Here’s an example:

product_code = 49
formatted_product_code = f'{product_code:0>5}'
print(formatted_product_code)

Output:

00049

This one-liner uses Python’s f-string with a similar formatting pattern as the str.format() method. It begins with an f before the quote and contains curly braces with an in-line expression and formatting details.

Summary/Discussion

  • Method 1: zfill(). Most straightforward, no need for additional formatting symbols. Limited to zero-padding.
  • Method 2: rjust(). Allows for padding with characters other than zero. Slightly less intuitive when zero-padding is solely needed.
  • Method 3: % formatting. Familiar to those coming from other languages with printf-style formatting. Considered somewhat outdated in modern Python.
  • Method 4: str.format(). Versatile and powerful, but syntax may be overkill for simple padding tasks. Very readable for complex formatting.
  • Method 5: f-Strings. The newest and often most concise method; combines inline expression with clear syntax. Only available in Python 3.6 and above.