如何解决如何从第二个字符串中的字符串中删除行?
我有两个字符串:
字符串 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)
但结果仍然包含来自第二个字符串的一些行...
解决方法
您可能在某些行的末尾有一些填充空格,并且 s1
和 s2
之间的数量不同,因此您可以使用 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))
,
我在 Python 3.8.5 上运行了你的代码,并得到了输出:
machine1 volume1 Mon May 24 00:00:10 2021
machine2 volume1 Mon May 24 00:00:03 2021
不包含来自字符串 B 的任何字符串。
也许看看你的字符串是如何格式化的,看看行尾是否有任何空格或奇怪的换行符会导致字符串比较?
,一个班轮,
sA = f'machine1 volume1 Mon May 24 00:00:10 2021\n\
machine2 volume1 Mon May 24 00:00:03 2021\n\
machine2 volume2 Mon May 24 00:00:03 2021'
sB = f'machine1 volume2 Mon May 23 00:00:10 2021 \n\
machine2 volume1 Mon May 23 00:00:03 2021\n\
machine2 volume2 Mon May 24 00:00:03 2021'
print('\n'.join(x for x in sA.splitlines() if x not in sB.splitlines()))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。