How do I remove the space in my output here when slicing?

Due to this exercise I wanted to come up with a function that gives you the last word of a string no matter how many words and spaces are inside that string.

Unfortunately, my function seems to output an empty space before the last words appears.

Here is the code (given in its entirety just in case - also I find it kind of cool):

def final_word(phrase):

  countindices = 0 

  spaces = 0

  listindices = []

  for items in range(len(phrase)):

    countindices += 1

    if phrase[items] == " ":

        spaces += 1

        listindices.append(countindices -1)

  if spaces == 0:

    return "There is only one word!"

  else:

    lastword = listindices[-1]

    return phrase[lastword:]

  

phrase1 = "wefawefawefergeg afaf afaf aaaaa"

print(final_word(phrase1))

I’m almost 100% certain the space is due to how I splice here in this line:

return phrase[lastword:]

However, even after playing around with splicing for a bit, I can’t seem to get rid of the initial space which is given in the output without ruining how the function works.

Thanks in advance for any replies.

I find the issue to be in this section. Your for loop is doing “for items in range(len(phrase))”, which means that items will start at 0 and go to len(phrase)-1. However your countindices that is used here is incremented as soon as the loop begins, meaning that it effectively starts from 1, not 0. I presume this is why you have added a -1 to the append() section, however what this means is that the indice that you are saving to listindices is essentially your variable items. Since this is only saved when phrase[items] is a space, this means that you are saving the indice where you find a space.

As an example to illustrate, the last word in your phrase starts at indice 27, with a space at indice 26. Therefore when items = 26, countindices = 27, it increments spaces by 1, and then appends countindices - 1 which we know to be 27-1 = 26. Therefore when you call phrase[lastword:], you are calling phrase[26] which we know to be a space!

Hopefully that makes it clear why the -1 is not required. And for clarity, here is your code with the fix on line 17.

def final_word(phrase): countindices = 0 spaces = 0 listindices = [] for items in range(len(phrase)): countindices += 1 if phrase[items] == " ": spaces += 1 listindices.append(countindices) if spaces == 0: return "There is only one word!" else: lastword = listindices[-1] return phrase[lastword:] phrase1 = "wefawefawefergeg afaf afaf aaaaa" print("'" + final_word(phrase1) + "'")
2 Likes