【问题标题】:Why my function doesn't return a new string?为什么我的函数不返回新字符串?
【发布时间】:2022-01-04 20:41:22
【问题描述】:

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

这是我的函数,但如果字符串不包含单词“exit”或“end”,则不会返回新字符串:

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"))

【问题讨论】:

标签: python string function replace


【解决方案1】:

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 将它们视为分隔符(即,甚至不是一个词)。

【讨论】:

    【解决方案2】:

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

    您可能想要for word in long.string.split(' ') 之类的东西来迭代单词。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-06
      • 2017-04-15
      • 1970-01-01
      • 2016-05-12
      • 2019-10-12
      • 1970-01-01
      • 2021-05-12
      • 2016-01-18
      相关资源
      最近更新 更多