如何从第二个字符串中的字符串中删除行?

2024-05-19 16:11:30 发布

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

我有两条线:

字符串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)

但是结果仍然包含第二个字符串中的一些行


Tags: 字符串inresultmayjoinsets2mon
3条回答

我在Python 3.8.5上运行了您的代码,得到了以下输出:

machine1 volume1 Mon May 24 00:00:10 2021 
machine2 volume1 Mon May 24 00:00:03 2021

它不包含字符串B中的任何字符串

也许可以研究一下字符串的格式,看看行的末尾是否有空格或奇数新行字符导致字符串比较失败

在某些行的末尾可能有一些填充空格,并且s1s2之间的填充空格量不同,因此可以使用rstrip()来解决这个问题

这将保留结果中的前导空格

avoid = {x.rstrip() for x in s2.splitlines()}
result = "\n".join(x for x in s1.splitlines() if x.rstrip() not in avoid)

这将删除结果中的前导空格

avoid = {x.rstrip() for x in s2.splitlines()}
result = "\n".join(x.rstrip() for x in s1.splitlines() if x.rstrip() not in avoid)

试试这个:

str1="machine1 volume1 Mon May 24 00:00:10 2021\nmachine2 volume1 Mon May 24 00:00:03 2021\nmachine2 volume2 Mon May 24 00:00:03 2021"
str2="machine1 volume2 Mon May 23 00:00:10 2021\nmachine2 volume1 Mon May 23 00:00:03 2021\nmachine2 volume2 Mon May 24 00:00:03 2021"
list1=str1.split("\n") #=== Convert to list
list2=str2.split("\n")
newlist=[x for x in list1 if x not in list2] #== list comprehension, if x in list2, add it to newlist
print(str(newlist)) 

相关问题 更多 >