Home > Software design >  Why my function doesn't return a new string?
Why my function doesn't return a new string?

Time:11-27

My assignment was to write a function with one string parameter that returns a string. The function should extract the words within this string, drop empty words as well as words that are equal to "end" and "exit", convert the remaining words to upper case, join them with the joining token string ";" and return this newly joined string.

This is my function but if the string doesnt contain the words "exit" or "end" no new string is returned:

def fun(long_string):
    stop_words = ('end', 'exit', '  ')
    new_line = ''

    for word in long_string:
        if word in stop_words:
            new_line = long_string.replace(stop_words, " ")

    result = ';'.join(new_line.upper())
    return result

print(fun("this is    a long string"))

CodePudding user response:

The condition of if is never True, since word is not a real "word"; word in your code will be each "character" of long_string. So what if really does here is comparing 't' with 'end' and so on. Therefore, new_line always remains to be the empty string as initialized.

You will need split to work with words:

def fun(long_string):
    return ';'.join(word for word in long_string.split() if word not in ('end', 'exit'))

print(fun("this is    a long string")) # this;is;a;long;string

You don't need to check for empty words, because split considers them as separators (i.e., not even a word).

CodePudding user response:

for word in long_string will iterate over each character in long_string, not each word. The next line compares each character to the words in stop_words.

You probably want something like for word in long.string.split(' ') in order to iterate over the words.

  • Related