Pythonでの文字列の整列方法の紹介

560 ワード

目的
文字列の左揃え、右揃え、中央揃えを実現します.
方法
文字列には以下の方法が組み込まれています.widthは文字列Sを含む幅を指し、fillcharはデフォルトでスペースです.塗りつぶし文字を指定することもできます.
 
  
string.ljust(s, width[, fillchar])
string.rjust(s, width[, fillchar])
string.center(s, width[, fillchar])
 
  
In [6]: a='Hello!'

In [7]: print a.ljust(10,'+')
Hello!++++

In [8]: print a.rjust(10,'+')
++++Hello!

In [9]: print a.center(10,'+')
++Hello!++