Incrosnatu Bogdan
Incrosnatu Bogdan

Reputation: 29

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:
        stripped.append(line.strip())

Upvotes: 0

Views: 3061

Answers (2)

James K
James K

Reputation: 3752

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

Upvotes: 3

Wayne Werner
Wayne Werner

Reputation: 51917

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 ========'

Upvotes: 4

Related Questions