Pad Numbers to Specified Length in Python

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, sometimes we need to pad a number with leading zeros to make it a certain length. For example, we might want to pad the number 7 to be 000007. In this challenge, you will need to write a function that pads a given number to the specified length.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/strings("`Strings`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13702{{"`Pad Numbers to Specified Length in Python`"}} python/variables_data_types -.-> lab-13702{{"`Pad Numbers to Specified Length in Python`"}} python/strings -.-> lab-13702{{"`Pad Numbers to Specified Length in Python`"}} python/type_conversion -.-> lab-13702{{"`Pad Numbers to Specified Length in Python`"}} python/tuples -.-> lab-13702{{"`Pad Numbers to Specified Length in Python`"}} python/function_definition -.-> lab-13702{{"`Pad Numbers to Specified Length in Python`"}} python/build_in_functions -.-> lab-13702{{"`Pad Numbers to Specified Length in Python`"}} end

Pad Number

Write a function pad_number(n, l) that takes in a number n and a length l and returns a string that represents the padded number. The function should pad the number with leading zeros to make it l digits long. If the number is already l digits long, the function should return the number as a string.

To pad the number, you can use the str.zfill() method. This method takes in a length and pads the string with leading zeros until it is that length. For example, "7".zfill(6) would return "000007".

def pad_number(n, l):
  return str(n).zfill(l)
pad_number(1234, 6); ## '001234'

Summary

In this challenge, you wrote a function that pads a given number to the specified length. You learned how to use the str.zfill() method to pad a string with leading zeros.

Other Python Tutorials you may like