如何在python中从字符串列表中删除多个不需要的字符?

2024-04-29 15:49:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下输入字符串:

text='''Although never is often better than *right* now.

If the implementation is hard to explain, it's a bad idea.

If the implementation is easy to explain, it may be a good idea.

Namespaces are one honking great idea -- let's do more of those!'''

到目前为止,我已经将text字符串拆分为list,如下所示:

^{pr2}$

现在,我想使用strip函数从上面的列表中删除不需要的字符,比如\n\n和{}。在

你能帮我一下吗??在


Tags: theto字符串textifisitimplementation
3条回答

使用re模块,^{}函数将允许您这样做。 我们需要用单个的\n替换multilpe\n出现,并删除字符串

import re

code='''Although never is often better than right now.

If the implementation is hard to explain, it's a bad idea.

If the implementation is easy to explain, it may be a good idea.

Namespaces are one honking great idea   let's do more of those!'''


result = re.sub('\n{2,}', '\n', code)
result = re.sub('   ', ' ', result)

print(result)

然后分割你的文本。在

您可以使用列表理解来删除

>>> code='''Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea   let's do more of those!'''
>>> 
>>> [word for word in code.split() if word != ' ']
['Although', 'never', 'is', 'often', 'better', 'than', 'right', 'now.', 'If', 'the', 'implementation', 'is', 'hard', 'to', 'explain,', "it's", 'a', 'bad', 'idea.', 'If', 'the', 'implementation', 'is', 'easy', 'to', 'explain,', 'it', 'may', 'be', 'a', 'good', 'idea.', 'Namespaces', 'are', 'one', 'honking', 'great', 'idea', "let's", 'do', 'more', 'of', 'those!']

这将使用空格或换行符拆分字符串

import re

output = [i for i in re.split(r'\s|\n{1:2}| ', code) if i]

相关问题 更多 >