361,975 views
24 votes
24 votes
#Write a function called align_right. align_right should #take two parameters: a string (a_string) and an integer #(string_length), in that or

User Kalyan Halder
by
2.4k points

1 Answer

17 votes
17 votes

Full question:

#Write a function called align_right. align_right should #take two parameters: a string (a_string) and an integer #(string_length), in that order. # #The function should return the same string with spaces #added to the left so that the text is "right aligned" in a #string. The number of spaces added should make the total #string length equal string_length. # #For example: align_right("CS1301", 10) would return the #string " CS1301". Four spaces are added to the left so #"CS1301" is right-aligned and the total string length is #10. # #HINT: Remember, len(a_string) will give you the number of #characters currently in a_string.

Answer and Explanation:

Comments have been used in the code to explain the program

Using Python

#first define the function with #parameters a_string and string_length

def align_right(ourString,stringLength):

#test to see if string is longer than the length passed

if len(ourString) > stringLength:

print(ourString)

#If not define variable aligned and use #rjust function to justify string to the #left leaving space left in stringLength

else:

aligned=ourString.rjust(stringLength)

#print the variable aligned

print(aligned)

#Call function align_right

align_right("jelly", 15)

User Ken Fehling
by
2.5k points