问题:用python中的分隔符分割字符串

如何__在定界符哪里分割此字符串

MATCHES__STRING

得到['MATCHES', 'STRING']?的输出

How to split this string where __ is the delimiter

MATCHES__STRING

To get an output of ['MATCHES', 'STRING']?


回答 0

您可以使用以下功能:string.split('__')

>>> "MATCHES__STRING".split("__")
['MATCHES', 'STRING']

You can use the function: string.split('__')

>>> "MATCHES__STRING".split("__")
['MATCHES', 'STRING']

回答 1

您可能对csv模块感兴趣,该模块是为逗号分隔的文件设计的,但可以轻松修改以使用自定义定界符。

import csv
csv.register_dialect( "myDialect", delimiter = "__", <other-options> )
lines = [ "MATCHES__STRING" ]

for row in csv.reader( lines ):
    ...

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.

import csv
csv.register_dialect( "myDialect", delimiter = "__", <other-options> )
lines = [ "MATCHES__STRING" ]

for row in csv.reader( lines ):
    ...

回答 2

如果字符串中有两个或多个(在下面的示例中有三个)元素,则可以使用逗号分隔以下各项:

date, time, event_name = ev.get_text(separator='@').split("@")

在这行代码之后,三个变量将具有变量ev的三个部分的值

因此,如果变量ev包含此字符串,并且我们应用分隔符’@’:

Sa.,23.März@ 19:00 @ Klavier + Orchester:SPEZIAL

然后,在拆分操作之后,变量

  • 日期的值将为“ Sa.,23.März”
  • 时间的值为“ 19:00”
  • event_name的值将为“ Klavier + Orchester:SPEZIAL”

When you have two or more (in the example below there’re three) elements in the string, then you can use comma to separate these items:

date, time, event_name = ev.get_text(separator='@').split("@")

After this line of code, the three variables will have values from three parts of the variable ev

So, if the variable ev contains this string and we apply separator ‘@’:

Sa., 23. März@19:00@Klavier + Orchester: SPEZIAL

Then, after split operation the variable

  • date will have value “Sa., 23. März”
  • time will have value “19:00”
  • event_name will have value “Klavier + Orchester: SPEZIAL”

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。