删除字符串从特定字符在python
问题描述:
开始我在一个文件中的以下数据:删除字符串从特定字符在python
Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd
10.230.2.91 4 136041 0 0 35w6d 1178
CHN_RAY_901_1AC_CASR903R004# exit
Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd
10.229.5.239 4 890585 0 0 7w5d 1177
10.229.6.239 4 890585 0 0 7w5d 1173
CHN_MAR_905_1AC_CASR903R066# exit
10.229.30.110
我必须删除从CHN开始的所有行,并且具有等的输出:
Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd
10.230.2.91 4 136041 0 0 35w6d 1178
Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd
10.229.5.239 4 890585 0 0 7w5d 1177
10.229.6.239 4 890585 0 0 7w5d 1173
10.229.30.110
我已尝试:
b = ' '.join(word for word in content.split(' ') if not word.startswith('CHN'))
其中content是我的数据我想从中删除CHN,但它不起作用。
你能提出一些方法来达到这个目的。这可以不使用正则表达式来完成吗?提前致谢。
答
它可能会更容易与各条线,而不是整个文件内容的工作:
with open("file") as f:
lines = [line for line in f if not line.startswith("CHN")]
filtered = "".join(lines)
答
for line in file:
if not line[0:3] == "CHN":
write_line
else:
remove_line
答
file = """ Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd
10.230.2.91 4 136041 0 0 35w6d 1178
CHN_RAY_901_1AC_CASR903R004# exit
Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd
10.229.5.239 4 890585 0 0 7w5d 1177
10.229.6.239 4 890585 0 0 7w5d 1173
CHN_MAR_905_1AC_CASR903R066# exit
10.229.30.110
"""
output = [line for line in file.splitlines() if not line.startswith('CHN')]
print "\n".join(output)
尝试'content.splitlines()',而不是'content.split(”“)' 。 –