Python如何根据列表中的项目从字符串中剥离字符串

标签 python string list strip

我有一个如下所示的列表:

exclude = ["please", "hi", "team"]

我有一个字符串如下:

text = "Hi team, please help me out."

我希望我的字符串看起来像:

text = ", help me out."

有效地去除列表中可能出现的任何单词 exclude

我尝试了以下:

if any(e in text.lower()) for e in exclude:
         print text.lower().strip(e)

但上面的 if 语句返回一个 bool 值,因此我得到以下错误:

NameError: name 'e' is not defined

我如何完成这项工作?

最佳答案

是这样的吗?

>>> from string import punctuation
>>> ' '.join(x for x in (word.strip(punctuation) for word in text.split())
                                                   if x.lower() not in exclude)
'help me out

如果您想保留 exclude 中不存在的单词的尾随/前导标点符号:

>>> ' '.join(word for word in text.split()
                             if word.strip(punctuation).lower() not in exclude)
'help me out.'

第一个相当于:

>>> out = []
>>> for word in text.split():
        word = word.strip(punctuation)
        if word.lower() not in exclude:
            out.append(word)
>>> ' '.join(out)
'help me out'

关于Python如何根据列表中的项目从字符串中剥离字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27057101/

相关文章:

c# - 将列表中的元素作为第一个元素的最快方法

python - 如何在Python中将直线方程添加到绘图上

python - 将单个字典值转换为列表?

python - numpy.memmap 用于字符串数组?

c++ - 字符串中的 a[0] 和 &a[0] 有什么区别

php - 删除 PHP 字符串中包括字符在内的所有内容

c# - 如何获取包含字符串的列表的索引

python - 使用 Python 标准化 JSON

python - 值错误 : could not convert string to float: id

Ruby:邮件列表库或 gem