Extra whitespace after final word...how do I remove it?



I understand exactly why this code return an extra white space after my last word, but I do not know how to fix my existing code to remove this...(without using an alternative method all together). Could someone help me add code that would allow me to always remove the last white space after the final word?

def censor(text, word):
    new_text = text.split(" ")
    censored = ""
    for wrd in new_text:
        if wrd == word:
            censored += ("*" * len(wrd) + " ")
            censored += (wrd + " ")
    return censored


You can use slicing to eliminate the space.


Using inbuilt function like rstrip()


Thank you! How would I be able to use rstrip() for this though...since isn't this method used to getting rid of a certain character (i.e. a whitespace) BUT throughout a string...and not just at the end of my string for example?


By defualt rstrip() will erase space character from right side of string.


You need to slice your string such that so it does not include last character as it is a space character.


It's no crime to build a list, then join it on return. That way there are no spaces to deal with.

temp = []
for term in words:
    if term == word:
        temp.append('*' * len(word))
return ' '.join(temp)


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.