どうも、ちょげ(@chogetarou)です。
文字列の先頭と末尾に空白を追加する方法を紹介します。
方法

文字列の前後に空白を入れる方法は、3つあります。
center()
1つ目は、center()を使う方法です。
まず、文字列からcenter()を呼び出します。
そして、center()の引数に、文字列の文字数に空白の数を足した値を指定します。
文字列の文字数は、引数に文字列を指定したlen()関数で取得します。
#countは空白の数
result = text.center(len(text) + count)
上記のcenter()は、呼び出した文字列の前後に空白を追加した文字列を返します。
使用例
text = "Hello,World"
result = text.center(len(text) + 10)
print(result, 'end')
出力:
Hello,World end
rjust()
2つ目は、rjust()を使う方法です。
まず、文字列からrjust()を呼び出します。
そして、rjust()の引数に文字列の文字数に空白の数を追加した値を指定します。
文字列の文字数は、引数に文字列を指定したlen()関数で取得します。
#countは追加する空白の数
result = text.rjust(len(text) + count)
上記のrjust()は、呼び出した文字列の先頭に空白を追加した文字列を返します。
使用例
text = "Hello,World"
result = text.rjust(len(text) + 5)
print(result)
出力:
Hello,World
ljust()
3つ目は、ljust()を使う方法です。
まず、文字列からljust()を呼び出します。
そして、ljust()の引数に文字列の文字数に空白の数を追加した値を指定します。
文字列の文字数は、引数に文字列を指定したlen()関数で取得します。
#countは追加する空白の数
result = text.ljust(len(text) + count)
上記のljust()は、呼び出した文字列の末尾に空白を追加した文字列を返します。
使用例
text = "Hello,World"
result = text.ljust(len(text) + 5)
print(result, 'end')
出力:
Hello,World end
まとめ
文字列の前後に空白を入れる方法は、次の3つです。
- center()を使う方法
result = text.center(len(text) + count)
- rjust()を使う方法
result = text.rjust(len(text) + count)
- ljust()を使う方法
result = text.ljust(len(text) + count)
コメント