用python中的分隔符分割字符串

时间:2022-02-06 02:47:51

How to split this string where $$TEXT$$ is the delimiter.

如何分割这个字符串,其中$$TEXT$$是分隔符。

  1.MATCHES$$TEXT$$STRING  
  2.MATCHES $$TEXT$$ STRING   

2 个解决方案

#1


195  

string.split('$$TEXT$$') ?

string.split(“$ $ $ $文本”)?

>>> a="1.MATCHES$$TEXT$$STRING"
>>> a.split("$$TEXT$$")
['1.MATCHES', 'STRING']

>>> a="2.MATCHES $$TEXT$$ STRING"
>>> a.split("$$TEXT$$")
['2.MATCHES ', ' STRING']

and:

和:

>>> [x.strip() for x in "2.MATCHES $$TEXT$$ STRING".split("$$TEXT$$")]
['2.MATCHES', 'STRING']

#2


4  

You may be interested in the csv module, which is designed for comma-separated files but can be easily modified to use a custom delimiter.

您可能对csv模块感兴趣,它是为逗号分隔的文件设计的,但是可以很容易地修改为使用自定义分隔符。

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 ):
    ...

#1


195  

string.split('$$TEXT$$') ?

string.split(“$ $ $ $文本”)?

>>> a="1.MATCHES$$TEXT$$STRING"
>>> a.split("$$TEXT$$")
['1.MATCHES', 'STRING']

>>> a="2.MATCHES $$TEXT$$ STRING"
>>> a.split("$$TEXT$$")
['2.MATCHES ', ' STRING']

and:

和:

>>> [x.strip() for x in "2.MATCHES $$TEXT$$ STRING".split("$$TEXT$$")]
['2.MATCHES', 'STRING']

#2


4  

You may be interested in the csv module, which is designed for comma-separated files but can be easily modified to use a custom delimiter.

您可能对csv模块感兴趣,它是为逗号分隔的文件设计的,但是可以很容易地修改为使用自定义分隔符。

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 ):
    ...