对包含多行字符串的列表执行正则表达式

2024-05-15 15:13:33 发布

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

我需要执行正则表达式来清理下面列表中的字符串

X = [ "This is a # scary wolf! ",
    "welcome to a mysterious  jungle",
    "2020 was the year to remember forever_never",
    "Remember the name s - John",
    "I      admire      you" ]

我觉得单独在字符串上执行正则表达式很舒服,但是当它们被放在列表中时,我很难理解如何处理这个示例

输出应该如下所示:

This is scary wolf 
welcome to mysterious jungle
was the year to remember forever
Remember the name John
I admire you

解决这个问题的最佳方法是什么


Tags: theto字符串列表isthisyearremember
1条回答
网友
1楼 · 发布于 2024-05-15 15:13:33

如果您对处理单个字符串感到满意,那么您可以编写一个函数,接收单个字符串并返回它

def your_regex_function(one_string):
    your code here that applies regular expressions to one_string
    return cleaned_string

然后,您需要使用该函数创建一个新的字符串列表,这可以通过列表理解来实现:

cleaned_string = [your_regex_function(element) for element in X]

列表理解将循环X的每个元素,运行函数,并将清理后的单个字符串作为新元素放入新列表中

相关问题 更多 >