Problem 3.3
Center Align
Write a program center_align.py
to center align all lines in the given file.
$ cat poem.txt
There was an Old Man with a beard
Who said, "It is just as I feared!
Two Owls and a Hen,
Four Larks and a Wren,
Have all built their nests in my beard!"
$ python center_align.py poem.txt
There was an Old Man with a beard
Who said, "It is just as I feared!
Two Owls and a Hen,
Four Larks and a Wren,
Have all built their nests in my beard!"
Hint:
>>> "hello".center(7)
" hello "
>>> "hello".center(9)
" hello "
The built-in function max
can take a list of numbers and return the maximum value out of them.
>>> max([1, 5, 2, 7, 4])
7
Solution
import sys
filename = sys.argv[1]
lines = open(filename).readlines()
if lines:
n = max(len(line.strip()) for line in lines)
for line in lines:
print(line.strip().center(n))