StacyM StacyM - 1 month ago 7
Python Question

Python Logic - Centering text using periods

I'm taking this intro to python course online

The problem reads:


For this program, the first line of input is an integer width. Then, there are some lines of text; the line "END" indicates the end of the text. For each line of text, you need to print out a centered version of it, by adding periods .. to the left and right, so that the total length of each line of text is width. (All input lines will have length at most width.) Centering means that the number of periods added to the left and added to the right should be equal if possible; if needed we allow one more period on the left than the right. For example, for input


13
Text
in
the
middle!
END


the correct output would be

.....Text....
......in.....
.....the.....
...middle!...


the Hint given is:


For input line length of L, you should add (width-L)\\2 periods to the right side


Here is my code so far:

width = int(input())
s1 = input()

periods_remain = width - len(s1)
L = periods_remain
periods_rtside = (width-L)//2
periods_leftside = width - periods_rtside
periods_rt_str = '.' * periods_rtside
periods_left_str = '.' * periods_leftside
line1 = periods_left_str + s1 + periods_rt_str


My line1 result looks like "...........Text.." Instead of .....Text....

It can be run here

My problem seems to be the L. I'm not sure how to define L. Thanks!

Answer

You can use str.center for this:

>>> lis = ['Text', 'in', 'the', 'middle!', 'END']
>>> for item in lis:
...     print item.center(13, '.')
...     
.....Text....
......in.....
.....the.....
...middle!...
.....END.....

or format:

for item in lis:
    print format(item,'.^13')
...     
....Text.....
.....in......
.....the.....
...middle!...
.....END.....

Working version of your code:

lis = ['Text', 'in', 'the', 'middle!', 'END']
width = 13
for s1 in lis:
    L = len(s1)                                    #length of line
    periods_rtside = (width - L)//2                #periods on the RHS
    periods_leftside = width - periods_rtside - L  #peroids on the LHS
    periods_rt_str = '.' * periods_rtside
    periods_left_str = '.' * periods_leftside
    line1 = periods_left_str + s1 + periods_rt_str
    print line1

output:

.....Text....
......in.....
.....the.....
...middle!...
.....END.....
Comments