Split a string by a delimiter in python

前端 未结 3 1350
名媛妹妹
名媛妹妹 2020-11-22 06:58

How to split this string where __ is the delimiter

MATCHES__STRING

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

相关标签:
3条回答
  • 2020-11-22 07:38

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

    >>> "MATCHES__STRING".split("__")
    ['MATCHES', 'STRING']
    
    0 讨论(0)
  • 2020-11-22 07:45

    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 ):
        ...
    
    0 讨论(0)
  • 2020-11-22 07:50

    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"
    0 讨论(0)
提交回复
热议问题