在python中通过分隔符分割字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3475251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:15:39  来源:igfitidea点击:

Split a string by a delimiter in python

pythonstringlistsplit

提问by Hulk

How to split this string where __is the delimiter

如何拆分此字符串__分隔符在哪里

MATCHES__STRING

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

得到['MATCHES', 'STRING']?

采纳答案by adamk

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

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

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

回答by Katriel

You may be interested in the csvmodule, 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 = "__", <other-options> )
lines = [ "MATCHES__STRING" ]

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

回答by Sergey Nasonov

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

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

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

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

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

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

Then, after split operation the variable

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

  • datewill have value "Sa., 23. M?rz"
  • timewill have value "19:00"
  • event_namewill have value "Klavier + Orchester: SPEZIAL"
  • 日期将具有值“Sa., 23. M?rz”
  • 时间将具有值“19:00”
  • event_name将具有值“Klavier + Orchester:SPEZIAL”