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


#1


https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/1/4?curriculum_id=4f89dab3d788890003000096#

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) + " ")
        else:
            censored += (wrd + " ")
    return censored


#2

You can use slicing to eliminate the space.

or

Using inbuilt function like rstrip()


#3

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?


#4

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

String.rstrip()

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


#5

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))
    else:
        temp.append(term)
return ' '.join(temp)

#6

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