challenge 文字列のセンタリング

文字列を指定のカラム幅にセンタリング配置する関数を示してください。文字列の長さが指定した幅より長い場合には文字列の両端をできるだけ均等に切り落して指定幅に収めてください。1文字は1カラムに収まるものと仮定してかまいません。

Posted feedbacks - Python

Pythonは組み込みでstr#center()を持ってたりするので一番楽かも。

Dan the Occasional Pythonista

P.S. perl の while(<>)、RubyのARGV.readlinesの代わりってpythonでどう書くのかにゃ?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#!/usr/bin/python

def center_and_crop(str, width = 80):
    margin = (width - len(str))/2
    if margin >= 0: return str.center(width)
    else:           return str[-margin:width-margin]

if __name__ == '__main__':
  import sys
  for line in sys.stdin:
    print center_and_crop(line[:-1], 72)

#         1         2         3         4         5         6         7
#12345678901234567890123456789012345678901234567890123456789012345678901
#This line is intentionally longer than 72 chars to test center_and_crop works \
fine.

if文もcenterメソッドも使わずに。

1
2
3
4
5
def center(s, n):
  return (' ' * n + a + ' ' * n)[(len(a)+n)/2:][:n]

print center('abc', 9)
print center('abc', 1)

Index

Feed

Other

Link

Pathtraq

loading...