Python-从字符串中删除所有标点符号,仅打印包含“ i”且等于或大于五个字符的单词

时间:2018-09-25 03:42:46

标签: python join split append

testText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque nec mauris nec tellus mollis ullamcorper. Vestibulum sit amet arcu placerat, sagittis quam sed, rutrum sem. Morbi vulputate odio non lacus."
splitText = testText.split(" ")
print(splitText)
cleanedText = ''
for letter in testText:
    if letter in list('.,:;?!'):
        cleanedText.append(letter)
''.join(cleanedText)

我正在尝试删除上面段落中的所有标点符号,但是遇到“属性错误:'str'对象没有属性'append'”。

可能出什么问题了,我应该如何解决呢?

此外,我该如何仅打印等于或大于五个字符的世界并包含'i'?

2 个答案:

答案 0 :(得分:0)

要删除一个简单的技巧,就是用一个空的str(用replace代替)。在第二部分中,我们看两个条件:单词中i,并且长度等于或大于5。请注意,我们以大写形式看I

testText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque nec mauris nec tellus mollis ullamcorper. Vestibulum sit amet arcu placerat, sagittis quam sed, rutrum sem. Morbi vulputate odio non lacus."
str_to_remove = list('.,:;?!')

for letter in str_to_remove:
    testText = testText.replace(letter, '')

for word in testText.split(' '):
    if 'i' in word and len(word) >= 5:
        print(word)

答案 1 :(得分:0)

尝试一下:

for letter in testText:
    if letter not in list('.,:;?!\''):
        cleanText += letter
print(cleanText)