我有两条线:
字符串A:
machine1 volume1 Mon May 24 00:00:10 2021
machine2 volume1 Mon May 24 00:00:03 2021
machine2 volume2 Mon May 24 00:00:03 2021
字符串B:
machine1 volume2 Mon May 23 00:00:10 2021
machine2 volume1 Mon May 23 00:00:03 2021
machine2 volume2 Mon May 24 00:00:03 2021
我想从字符串A中“删除”字符串B中的所有行,因此结果可能类似于:
新字符串A:
machine1 volume1 Mon May 24 00:00:10 2021
machine2 volume1 Mon May 24 00:00:03 2021
我试过这个:
avoid = set(s2.splitlines())
result = "\n".join(x for x in s1.splitlines() if x not in avoid)
print (result)
但是结果仍然包含第二个字符串中的一些行
我在Python 3.8.5上运行了您的代码,得到了以下输出:
它不包含字符串B中的任何字符串
也许可以研究一下字符串的格式,看看行的末尾是否有空格或奇数新行字符导致字符串比较失败
在某些行的末尾可能有一些填充空格,并且
s1
和s2
之间的填充空格量不同,因此可以使用rstrip()
来解决这个问题这将保留结果中的前导空格
这将删除结果中的前导空格
试试这个:
相关问题 更多 >
编程相关推荐