131k views
0 votes
#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.

User Aherrick
by
7.7k points

1 Answer

2 votes

Final answer:

The align_right function adds spaces to the left of the input string to right-align it within a string of a specified total length.

Step-by-step explanation:

The function align_right is designed to take as input a string (a_string) and an integer (string_length) and return a new string with spaces added to the left so that a_string is right-aligned within a string of total length string_length. To do this, first calculate the difference between string_length and the length of a_string using len(a_string). Then, prepend spaces to a_string equal to this difference. Here's how you could write this function in Python:

def align_right(a_string, string_length):
space_padding = ' ' * (string_length - len(a_string))
return space_padding + a_string

For example, align_right("CS1301", 10) would return " CS1301", with four spaces added to the left of "CS1301" to ensure the total string length is 10 characters.

User Stephen Reindl
by
7.3k points