[Python]文字列を空白埋めするには?

python

どうも、ちょげ(@chogetarou)です。

文字列を空白埋めする方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

文字列を空白埋めする方法は、3つあります。

center()

1つ目は、center()を使う方法です。

まず、文字列からcenter()を呼び出します。

そして、center()の引数に文字数を指定します。

result = text.center(文字数)

上記のcenter()は、引数の文字数に足りない分、左右に空白を埋めた文字列を返します。

使用例

text = "Hello,World"

result = text.center(20)

print(result, "end")
出力: 
    Hello,World      end

rjust()

2つ目は、rjust()を使う方法です。

まず、文字列からrjust()を呼び出します。

そして、rjust()の引数に文字数を指定します。

result = text.rjust(文字数)

上記のrjust()は、引数の文字数に足りない分を、左側に空白を埋めた文字列を返します。

使用例

text = "Hello,World"

result = text.rjust(20)

print(result)
出力: 
         Hello,World

ljust()

3つ目は、ljust()を使う方法です。

まず、文字列からljust()を呼び出します。

そして、ljust()の引数に文字数を指定します。

result = text.ljust(文字数)

上記のljust()は、引数の文字数に足りない分、左側に空白を埋めた文字列を返します。

使用例

text = "Hello,World"

result = text.ljust(20)

print(result, "end")
出力: 
Hello,World          end
スポンサーリンク

まとめ

文字列を0埋めする方法は、次の3つです。

  • center()を使う方法
    result = text.center(文字数)
  • rjust()を使う方法
    result = text.rjust(文字数)
  • ljust()を使う方法
    result = text.ljust(文字数)

コメント

タイトルとURLをコピーしました