2017-04-11 61 views
1

我正在讀取包含Linux樹輸出的文件的腳本,我想刪除每行開頭的樹格式。但是,我想保留字符串後的第一個字母或數字的間距。Python刪除字符,直到字母或數字

這是我到目前爲止有:

import re 
with open(tree_loc) as f: 
    for line in f: 
     if 'batman' in line: 
      line = re.sub(r'[^\w*]', '', line) 
      print(line) 
+0

嘗試're.sub(r'^ \ W +','',line)' –

回答

1

如何非正則表達式的解決方案?

>>> from string import letters, digits 
>>> from itertools import dropwhile 
>>> 
>>> keep = set(letters + digits) 
>>> s = '[email protected]@^test123' 
>>> ''.join(dropwhile(lambda c: c not in keep, s)) 
'test123' 
+1

完美的工作!謝謝你的幫助! –

相關問題