In: Computer Science
Copy-paste the given function header (with or without the docstring) into the answer window and then complete the body of the function. Then below, write the call expressions that match the given test cases, printing out the returned results of each call expression.
For full marks:
def centre_align(s: str) -> str:
""" Returns a string that contains s "centred"
and "highlighted"
when it is displayed on
a single line on a typical screen.
Highlighting is to be
done with the addition the
SAME number of *'s
before AND after the string itself. The number of
stars should fill the
line but not overfill it.
(Look at the test cases
to understand).
The typical screen width
is truly 80 characters wide
but to make things
easier on the exam, we will assume
that the typical screen
width is 20 characters wide.
Assume that s is a valid
string of length 1 to 20 characters
You do not have to
handle exceptional cases in this question.
>>>
centre_align('my title')
'******my
title******'
>>>
centre_align ('a')
'*********a*********'
>>>
centre_align('012345678901234567890')
'012345678901234567890'
We get the length fo the string using the len() function. Then we get the total number of '*' to be padded by subtracting 20. We pad the string with stars and return the new string.
Code:
def centre_align(s):
l = len(s)
stars = 20 - l#total number of stars assuming the total length is 20
#left and right stars are divided
leftStar = int(stars/2)
rightStar = int(stars/2)
s = ('*' * leftStar) + s + ('*' * rightStar)
return s
print(centre_align('my title'))
print(centre_align('a'))
print(centre_align('12345678901234567890'))
Code screenshot:
Output: