Python 文字幅の調整方法
Pythonでは、文字列の幅を設定するために、str.ljust()、str.rjust()、str.center()メソッドを使用します。
- str.ljust(width[, fillchar])メソッドはwidthで左詰めされた文字列を返します。fillcharが指定された場合は、fillcharを詰め文字として使用します(デフォルトはスペース)。
サンプルコード:
s = "Hello"
width = 10
fillchar = "-"
result = s.ljust(width, fillchar)
print(result) # 输出:Hello-----
- str.rjust(width[, fillchar])メソッドは width 幅で右揃えされた文字列を返します。fillchar パラメータが指定された場合は、fillchar を空白(既定)の代わりに空白として使用します。
サンプルコード:
s = "Hello"
width = 10
fillchar = "-"
result = s.rjust(width, fillchar)
print(result) # 输出:-----Hello
- str.center(幅, [フィル文字])メソッドでは、指定した幅の文字列を中央寄せして返す。フィル文字引数を指定する場合は、フィル文字(初期値は空白)が埋める。
サンプルコードをご提供ください。
s = "Hello"
width = 10
fillchar = "-"
result = s.center(width, fillchar)
print(result) # 输出:--Hello---
これらのメソッドを利用することで、文字列幅と配置を簡単に設定できます。