在 Python 中将数字填充到指定长度

PythonPythonBeginner
立即练习

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

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在 Python 中,有时我们需要用前导零填充一个数字,使其达到特定的长度。例如,我们可能想把数字 7 填充为 000007。在这个挑战中,你需要编写一个函数,将给定的数字填充到指定的长度。


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/variables_data_types("Variables and Data Types") python/BasicConceptsGroup -.-> python/strings("Strings") python/BasicConceptsGroup -.-> python/comments("Comments") 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/variables_data_types -.-> lab-13702{{"在 Python 中将数字填充到指定长度"}} python/strings -.-> lab-13702{{"在 Python 中将数字填充到指定长度"}} python/comments -.-> lab-13702{{"在 Python 中将数字填充到指定长度"}} python/type_conversion -.-> lab-13702{{"在 Python 中将数字填充到指定长度"}} python/tuples -.-> lab-13702{{"在 Python 中将数字填充到指定长度"}} python/function_definition -.-> lab-13702{{"在 Python 中将数字填充到指定长度"}} python/build_in_functions -.-> lab-13702{{"在 Python 中将数字填充到指定长度"}} end

填充数字

编写一个函数 pad_number(n, l),它接受一个数字 n 和一个长度 l,并返回一个表示填充后数字的字符串。该函数应该用前导零填充数字,使其长度为 l 位。如果数字本身已经是 l 位长,则函数应将该数字作为字符串返回。

要填充数字,你可以使用 str.zfill() 方法。此方法接受一个长度,并使用前导零填充字符串,直到达到该长度。例如,"7".zfill(6) 将返回 "000007"

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

总结

在这个挑战中,你编写了一个函数,用于将给定数字填充到指定长度。你学习了如何使用 str.zfill() 方法用前导零填充字符串。