为什么我的函数没有 return 新字符串?

Why my function doesn't return a new string?

我的任务是编写一个带有一个字符串参数的函数,return是一个字符串。该函数应提取此字符串中的单词,删除空单词以及等于“end”和“exit”的单词,将 剩余单词大写,将它们与连接标记字符串“;”连接起来return 这个 新加入的字符串。

这是我的函数,但如果字符串不包含单词“exit”或“end”,则不会 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"))

for word in long_string 将遍历 long_string 中的每个字符,而不是每个单词。下一行将每个字符与 stop_words.

中的单词进行比较

您可能需要类似 for word in long.string.split(' ') 的东西来遍历单词。

if 的条件永远不会是 True,因为 word 不是一个真正的“词”; word 在您的代码中将是 long_string 的每个“字符”。所以 if 在这里真正做的是比较 't''end' 等等。因此,new_line 始终保持为初始化时的空字符串。

您将需要 split 来处理单词:

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

您不需要检查空词,因为 split 将它们视为分隔符(即,甚至不是一个词)。