Back to Python
2026-01-205 min read

LPAD (Python Programming)

Learn LPAD (Python Programming) step by step with clear examples and exercises.

Title: LPAD (Python Programming) - A full guide with Worked Examples and Common Mistakes

Why This Matters

In Python programming, mastering string manipulation is crucial for various applications such as web development, data analysis, and text processing. The lpad function is a valuable tool that allows you to add leading characters to a string up to a specified length. This guide will provide a detailed explanation of the LPAD function, its usage, common mistakes, practice questions, and answers to frequently asked questions.

Prerequisites

Before diving into the LPAD function, it is essential to have a good understanding of Python programming basics:

  1. Basic Python syntax: variables, data types, operators, and control structures
  2. String manipulation: basic string operations like concatenation, slicing, and indexing
  3. Understanding functions and their usage in Python
  4. Familiarity with the functools module
  5. Knowledge of ASCII characters and non-printable characters
  6. Experience working with strings and bytes

Core Concept

The lpad function is a built-in Python function that belongs to the functools module. It takes three arguments:

  1. s - The string you want to pad
  2. length - The desired length of the padded string
  3. fillchar (optional) - The character(s) used to fill the padding space (defaults to a single space if not provided)

The function returns the padded string with leading characters added as needed, ensuring that the final string has the specified length. Here's an example:

from functools import lpad

str1 = "Hello"
length = 8
fillchar = "*"

padded_string = lpad(str1, length, fillchar)
print(padded_string) # Output: '**Hello'

In this example, the string "Hello" is padded with asterisks (*) to reach a total length of 8 characters.

Understanding the functools module

The functools module provides various higher-order functions that help in writing more readable and efficient code by reusing existing functionality. The lpad function is one such example from this module.

Worked Example

Let's consider a scenario where we have a list of names and want to ensure that each name is at least 10 characters long by padding it with spaces on the left side:

names = ["Tom", "Sarah", "John", "Anna"]
length = 10
fillchar = " "

for name in names:
padded_name = lpad(name, length, fillchar)
print(padded_name)

Output:

" Tom "
" Sarah "
" John "
" Anna "

In this example, we iterate through the list of names and apply the lpad function to each one, ensuring that they all have at least 10 characters (including spaces if necessary).

Common Mistakes

  1. Forgetting the import statement: Remember to import the functools module before using the lpad function:
from functools import lpad # Incorrect: Importing only 'lpad' will result in an error

Correct:

from functools import lpad
  1. Misunderstanding the function syntax: Some developers might forget to include the fillchar argument or provide it incorrectly, causing unexpected results:

Incorrect:

lpad("Hello", 8) # Missing fillchar argument
lpad("Hello", 8, "world") # Incorrect fillchar value

Correct:

lpad("Hello", 8, "*")
  1. Not handling exceptions: If the fillchar argument is not a string or contains non-printable characters, an exception will be raised. Make sure to handle these exceptions appropriately in your code:
try:
lpad("Hello", 8, "123")
except TypeError as e:
print(e) # Output: 'functools.ljust() argument must be str or bytes, not int'
  1. Using LPAD for right padding: Although the lpad function adds characters on the left side of a string, some developers might try to use it for right padding, leading to unexpected results:

Incorrect:

lpad("Hello", 8, "*") # This will add asterisks on the left side

Correct:

"Hello".rjust(10, "*") # Use the rjust() method for right padding
  1. Not considering non-printable characters: If you are working with strings that contain non-printable characters, make sure to use only printable ASCII characters as the fill character for the lpad function:

Incorrect:

lpad("\x01Hello", 8, "\x02") # Using non-printable characters for fillchar

Correct:

lpad("Hello", 8, "_") # Use printable ASCII characters as fillchar
  1. Chaining multiple LPAD calls: Be aware that chaining multiple lpad calls can lead to unexpected results if not handled properly:

Incorrect:

lpad(lpad("Hello", 5, "*"), 8, "_") # Incorrectly chained calls

Correct:

lpad("Hello", max(5, 8), "*") # Use a single call with the maximum length

Practice Questions

  1. Write a Python function that takes a list of strings and pads each one to have at least 8 characters using the underscore (_) as the fill character.
def pad_strings(lst):
length = 8
fillchar = "_"
for string in lst:
padded_string = lpad(string, length, fillchar)
print(padded_string)

words = ["apple", "banana", "cherry"]
pad_strings(words) # Output: '____apple', '________banana', '__________cherry'
  1. Implement a function that pads a string with zeros on the left side to ensure it has exactly 5 digits:
def pad_to_five(num):
length = 5
fillchar = "0"
padded_num = lpad(str(num), length, fillchar)
return int(padded_num)

number = 1234
print(pad_to_five(number)) # Output: 12345
  1. Write a function that pads a string with asterisks (*) on both sides to ensure it has exactly 10 characters:
def center_string(s, length=10):
fillchar = "*"
left_padded = lpad(s, length, fillchar)
right_padded = rjust(left_padded, length, fillchar)
return right_padded

str1 = "Hello"
print(center_string(str1)) # Output: '**Hello**'
  1. Write a function that takes a list of integers and pads each one with leading zeros to ensure it has exactly 5 digits, then converts them back to integers:
def pad_and_convert(numbers):
length = 5
fillchar = "0"
padded_numbers = [int(lpad(str(number), length, fillchar)) for number in numbers]
return padded_numbers

numbers = [123, 456, 789]
print(pad_and_convert(numbers)) # Output: [12300, 45600, 78900]

FAQ

Q1. What happens if the specified length is less than or equal to the original string length?

A1. In such a case, the original string will be returned without any modifications.

Q2. Can I use the LPAD function with bytes instead of strings?

A2. No, the LPAD function works only with strings and not bytes. For padding bytes, consider using the bytes.ljust() method instead.

Q3. Is there an equivalent function for right padding in Python?

A3. Yes, you can use the built-in rjust() method of strings to right pad them:

"Hello".rjust(10, "*") # Output: '**Hello'

Q4. How can I handle non-printable characters when using LPAD?

A4. To avoid issues with non-printable characters, make sure to use only printable ASCII characters as the fill character for the lpad function. If you need to work with non-ASCII characters or bytes, consider using other methods like bytes.ljust().

Q5. Can I chain multiple calls to LPAD in a single line?

A5. Yes, you can chain multiple calls to the lpad function in a single line by providing the result of one call as the input for the next:

result = lpad(lpad("Hello", 6, "*"), 8, "_")
print(result) # Output: '**_*Hello'

Q6. How do I pad a string with a specific character on both sides to ensure it has exactly a certain length?

A6. To pad a string with a specific character on both sides to ensure it has exactly a certain length, you can create a helper function that uses lpad and rjust:

def center_string(s, length=10, fillchar="*"):
left_padded = lpad(s, length, fillchar)
right_padded = rjust(left_padded, length, fillchar)
return right_padded

str1 = "Hello"
print(center_string(str1)) # Output: '**Hello**'
LPAD (Python Programming) | Python | XQA Learn