Pointing out the mistakes/unnecessary lines in your code:
-
The line
split = strings.split().upper()is erroneous and at the same time unnecessary as you are mistakenly usingstrings(list) instead ofstring(string literal). Also, you can uselen(string)directly instead of splitting the string into a list and finding the length of list. -
result.append(char * '#')is just appending “#” but not the actual string. The line could be rewritten asresult.append(string.upper() + char * '#')
Thus, your code can be re-written as following:
def squigler(strings):
result = []
for string in strings:
if len(string) < 5:
char = 5 - len(string)
result.append(string.upper() + char * '#')
else:
result.append(string.upper())
return result
An elegant way to achieve this would be the following:
def squigler(strings):
return list(map(lambda x: x.upper().ljust(5, '#'), strings))
Testing the Output
# TEST
strings = ['Right', 'SAID', 'jO']
strings = squigler(strings) # Over-writes the original `strings` list
print(strings) # Output: ['RIGHT', 'SAID#', 'JO###']
Here,
mapfunction loops over all the elements in the liststringsand
applieslambdafunction that we provided as an argument tomapto each of
these elements and returns amapobject which we then convert tolistand
return it.
ljustmethod of string, pushes the string to the left and appends a given character at the end of the string which would make the string exactly n characters long (in this case n=5)
EDIT:
In your case, since you are not allowed to change the test code, there’s an alternative in which you change the value of the list in-place instead of returning a new list…
def squigler(strings):
for(index, string) in enumerate(strings):
if len(string) < 5:
char = 5 - len(string)
strings[index] = string.upper() + char * '#'
else:
strings[index] = string.upper()
Here, you are changing the values of the list index-by-index
instead of returning a new list and reassigning the old one.
6
solved Make list of strings uppercase and fill up strings with less than 5 characters [closed]