在python中用分隔符分割一个string
如何分割这个string$$ TEXT $$是分隔符。
1.MATCHES$$TEXT$$STRING 2.MATCHES $$TEXT$$ STRING
string.split('$$TEXT$$')
?
>>> a="1.MATCHES$$TEXT$$STRING" >>> a.split("$$TEXT$$") ['1.MATCHES', 'STRING'] >>> a="2.MATCHES $$TEXT$$ STRING" >>> a.split("$$TEXT$$") ['2.MATCHES ', ' STRING']
和:
>>> [x.strip() for x in "2.MATCHES $$TEXT$$ STRING".split("$$TEXT$$")] ['2.MATCHES', 'STRING']
您可能对csv
模块感兴趣,它是为逗号分隔文件而devise的,但可以很容易地修改为使用自定义分隔符。
import csv csv.register_dialect( "myDialect", delimiter = "$$TEXT", <other-options> ) lines = [ "1.MATCHES$$TEXT$$STRING", "2.MATCHES $$TEXT$$ STRING" ] for row in csv.reader( lines ): ...