【发布时间】:2017-11-29 21:21:05
【问题描述】:
我正在尝试裁剪字符串列表的一部分并打印它们。数据如下所示 -
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
【问题讨论】:
-
我收到以下错误 -
AttributeError: 'str' object has no attribute 'groups'(在帖子中更新了我的代码) -
不能有任何组,它是
re.sub,它会删除匹配项。