Py学习  »  Python

Python不会删除单词,但适用于单个字母

dan123 • 3 年前 • 1389 次点击  

我有一个项目,我应该使用下面的代码从语句中删除一些单词:

forbidden_words = ["And","is","to","from","the"]
f = "And thus brought us to this conclusion from the existing inference"

h = []
for i in f:
    if i not in forbidden_words:
        h.append(i)
"".join(h)

输出: 'And thus brought us to this conclusion from the existing inference'

预期产出: 'thus brought us this conclusion existing inference'

我不知道为什么,但它适用于单个字母,但不适用于单个单词,假设代码如下:

forbidden_words = ["u","t","c","b","a"]
f = "And thus brought us to this conclusion from the existing inference"

h = []
for i in f:
    if i not in forbidden_words:
        h.append(i)
"".join(h)

输出: 'And hs rogh s o his onlsion from he exising inferene'

为什么会这样?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129817
 
1389 次点击  
文章 [ 3 ]  |  最新文章 3 年前