In: Computer Science
python
Write a function pack_to_5(words) that takes a list of string objects as a parameter and returns a new list containing each string in the title-case version. Any strings that have less than 5 characters needs to be expanded with the appropriate number of space characters to make them exactly 5 characters long. For example, consider the following list:
words = ['Right', 'SAID', 'jO']
The new list would be:
['Right', 'Said ', 'Jo ']
Since the second element only contains 4 characters, an extra space must be added to the end. The third element only contains 2 characters, so 3 more spaces must be added.
Note:
For example:
Test | Result |
---|---|
words = ['Right', 'SAID', 'jO'] result = pack_to_5(words) print(words) print(result) |
['Right', 'SAID', 'jO'] ['Right', 'Said ', 'Jo '] |
words = ['help', 'SAID', 'jO', 'FUNNY'] result = pack_to_5(words) print(words) print(result) |
['help', 'SAID', 'jO', 'FUNNY'] ['Help ', 'Said ', 'Jo ', 'Funny'] |
result = pack_to_5([]) print(result) |
[] |
Code:
def pack_to_5 (words): #pack_to_5() function
final_result=[] #final_result[] list
for word in [word.title() for word in words]: #for each word in
words convert it to title case and take every word in that
if (len(word)!=5): #check if the word lenght is 5 or not if not
5
diff=5-len(word) #take the difference of 5-length(word)
spaces=diff * ' ' #take string and store the number of spaces
word=word+(spaces) #finally concatenate the spaces
final_result.append(word) #finally append the word to final_result
list
return final_result #return final_result
print("Test Case-1")
words = ['Right', 'SAID', 'jO'] #test case 1 input list
result = pack_to_5 (words) #call pack_to_5(words) and store the
returned result
print(words)
print(result) #print result
print("\nTest Case-2")
words=['help','SAID','jO','FUNNY'] #test case 2 input list
result = pack_to_5 (words) #call pack_to_5(words1) and store the
returned result
print(words)
print(result) #print result
print("\nTest Case-3")
words=[] #test case 3 input list
result = pack_to_5 (words) #call pack_to_5(words2) and store the
returned result
print(words)
print(result) #print result
Code and Output Screenshots:
Note : For better understanding i have added a print statement for displaying each test case . we can remove that print statement if we want only input and output list.
Note : if you have any queries please post a comment thanks a lot..always available to help you...