Skip to main content
 首页 » 编程设计

python之裁剪出字符串的一部分并使用正则表达式打印

2025年01月19日28qq号

我正在尝试裁剪字符串列表的一部分并打印它们。数据如下所示 -

Books are on the table\nPick them up 
Pens are in the bag\nBring them 
Cats are roaming around 
Dogs are sitting 
Pencils, erasers, ruler cannot be found\nSearch them 
Laptops, headphones are lost\nSearch for them 

(这只是文件中100行数据中的几行)

我必须裁剪第 1、2、5、6 行中\n 之前的字符串并打印它们。我还必须与它们一起打印第 3,4 行。预期输出 -

Books are on the table 
Pens are in the bag 
Cats are roaming around 
Dogs are sitting 
Pencils erasers ruler cannot be found 
Laptops headphones are lost 

到目前为止我尝试了什么-

首先,我将 comma 替换为 space - a = name.replace(',',' ');

然后我使用正则表达式裁剪出子字符串。我的正则表达式是 - b = r'.*-\s([\w\s]+)\\n'。我无法打印 \n 不存在的第 3 行和第 4 行。

我现在收到的输出是 -

Books are on the table 
Pens are in the bag 
Pencils erasers ruler cannot be found 
Laptops headphones are lost 

我应该在表达式中添加什么来打印第 3 行和第 4 行?

TIA

请您参考如下方法:

您可以匹配并删除以反斜杠和 n 的组合开头的行部分,或所有标点符号(非单词和非空白)字符使用re.sub :

a = re.sub(r'\\n.*|[^\w\s]+', '', a) 

参见 regex demo

详情

  • \\n.* - \、n,然后是该行的其余部分
  • | - 或者
  • [^\w\s]+ - 除了单词和空白字符之外的 1 个或多个字符

如果你需要确保\n后面有一个大写字母,你可以在模式中的n之后添加[A-Z] .