如何从python中的字符串的开头和结尾删除特殊字符

时间:2018-04-08 04:33:11

标签: python

我有一个句子列表,其中包含字符串末尾的特殊字符(!?@#$。)。我需要去除它们。以下是句子列表:

['The first time you see The Second Renaissance it may look boring.', 'Look at it at least twice and definitely watch part 2.', 'It will change your view of the matrix.', 'Are the human people the ones who started the war?', 'Is AI a bad thing?']

我的输出应该是这样的:

['The first time you see The Second Renaissance it may look boring', 'Look at it at least twice and definitely watch part 2', 'It will change your view of the matrix', 'Are the human people the ones who started the war', 'Is AI a bad thing']

3 个答案:

答案 0 :(得分:2)

如果您只想从开头和结尾删除字符,可以使用string.strip()方法。

示例:

strp_chars = '!?@#$.'
sentence = 'The first time you see The Second Renaissance it may look boring.'
print(sentence.strip(strp_chars))

答案 1 :(得分:1)

在列表压缩中,只需将string.strip与您需要删除的所有字符一起使用,例如:

In [1]: l = ['The first time you see The Second Renaissance it may look boring.', 'Look at it at least twice and definitely watch part 2.', 'It will change
   ...:  your view of the matrix.', 'Are the human people the ones who started the war?', 'Is AI a bad thing?']

In [2]: p = [i.strip('.,?!') for i in l]

In [3]: p
Out[3]:
['The first time you see The Second Renaissance it may look boring',
 'Look at it at least twice and definitely watch part 2',
 'It will change your view of the matrix',
 'Are the human people the ones who started the war',
 'Is AI a bad thing']

In [4]:

答案 2 :(得分:0)

您可以尝试翻译方法:

import unicodedata
import sys

data1=['The first time you see The Second Renaissance it may look boring.', 'Look at it at least twice and definitely watch part 2.', 'It will change your view of the matrix.', 'Are the human people the ones who started the war?', 'Is AI a bad thing?']


data=dict.fromkeys([i for i in range(sys.maxunicode) if unicodedata.category(chr(i)).startswith('P')])

def remove_punctuation(sentence):
    return sentence.translate(data)

for i in data1:
    print(remove_punctuation(i))

输出:

The first time you see The Second Renaissance it may look boring
Look at it at least twice and definitely watch part 2
It will change your view of the matrix
Are the human people the ones who started the war
Is AI a bad thing