在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
Split a string by a delimiter in python
提问by Hulk
How to split this string where __is the delimiter
如何拆分此字符串__分隔符在哪里
MATCHES__STRING
To get an output of ['MATCHES', 'STRING']?
得到['MATCHES', 'STRING']?
采纳答案by adamk
回答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”

