Skip to content Skip to sidebar Skip to footer

How Do I Centre Align A Text From A File

This is my basic code but I don't know what to add after the def def centre(s, width=70): lines = open ('poem.txt ', 'r'). readlines () stripped = [] for line in lines:

Solution 1:

You may want to look into the str.format() function. If you read the documentation you'll find that it has the ability to center text:

>>> "{0:^40}".format(" Ministry of Silly Walks ")
'        Ministry of Silly Walks         '
>>> "{0:=^40}".format(" Ministry of Silly Walks ")
'======= Ministry of Silly Walks ========'

Solution 2:

python provides a str.center(width[,fillchar]) method.

for line in lines:
   print(line.center(width))

or similar

http://docs.python.org/3/library/stdtypes.html#string-methods


Post a Comment for "How Do I Centre Align A Text From A File"