簡體   English   中英

從python中的特定字符開始刪除字符串

[英]Remove string starting from specific characters in 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'))

我要從中刪除CHN的內容是我的數據,但是它不起作用。

您能否提出實現此目標的方法? 不使用正則表達式就可以做到嗎? 提前致謝。

使用單個行而不是整個文件內容可能會更容易:

with open("file") as f:
    lines = [line for line in f if not line.startswith("CHN")]
    filtered = "".join(lines)
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)
for line in file:
  if not line[0:3] == "CHN":
    write_line
  else:
    remove_line

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM