Python で文字列を指定された長さにパディングする

PythonPythonBeginner
今すぐ練習

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

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

Python では、時々特定の文字で文字列をパディングして、特定の長さにする必要があります。たとえば、文字列を両端に空白でパディングして、特定の長さにすることができます。このチャレンジでは、指定された文字で文字列を両端にパディングする関数を書くことが求められます。文字列が指定された長さより短い場合です。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/default_arguments("Default Arguments") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/ModulesandPackagesGroup -.-> python/using_packages("Using Packages") python/ModulesandPackagesGroup -.-> python/standard_libraries("Common Standard Libraries") python/PythonStandardLibraryGroup -.-> python/math_random("Math and Random") subgraph Lab Skills python/comments -.-> lab-13703{{"Python で文字列を指定された長さにパディングする"}} python/tuples -.-> lab-13703{{"Python で文字列を指定された長さにパディングする"}} python/function_definition -.-> lab-13703{{"Python で文字列を指定された長さにパディングする"}} python/default_arguments -.-> lab-13703{{"Python で文字列を指定された長さにパディングする"}} python/build_in_functions -.-> lab-13703{{"Python で文字列を指定された長さにパディングする"}} python/importing_modules -.-> lab-13703{{"Python で文字列を指定された長さにパディングする"}} python/using_packages -.-> lab-13703{{"Python で文字列を指定された長さにパディングする"}} python/standard_libraries -.-> lab-13703{{"Python で文字列を指定された長さにパディングする"}} python/math_random -.-> lab-13703{{"Python で文字列を指定された長さにパディングする"}} end

文字列をパディングする

指定された文字で文字列を両端にパディングする関数 pad(s: str, length: int, char: str ='') -> str を書きます。文字列が指定された長さより短い場合です。この関数は3つのパラメータを受け取る必要があります。

  • s: パディングする必要のある文字列
  • length: パディングされた文字列の合計長を指定する整数
  • char: 文字列をパディングするために使用される文字。デフォルト値は空白文字です。

この関数はパディングされた文字列を返す必要があります。

from math import floor

def pad(s, length, char =''):
  return s.rjust(floor((len(s) + length)/2), char).ljust(length, char)
pad('cat', 8) #' cat   '
pad('42', 6, '0') ## '004200'
pad('foobar', 3) ## 'foobar'

まとめ

このチャレンジでは、文字列が指定された長さより短い場合、指定された文字で文字列を両端にパディングする方法を学びました。与えられた文字列を両端にパディングするために、str.ljust()str.rjust() メソッドを使用しました。また、空白文字をデフォルトのパディング文字として使用する方法も学びました。