Asked  7 Months ago    Answers:  5   Viewed   37 times

How to split this string where __ is the delimiter

MATCHES__STRING

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

 Answers

32

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

>>> "MATCHES__STRING".split("__")
['MATCHES', 'STRING']
Tuesday, June 1, 2021
 
liquidmotion
answered 7 Months ago
19

You could use itertools.groupby to group lines that occur after :Entry into lists:

import itertools as it
filename='test.dat'

with open(filename,'r') as f:
    for key,group in it.groupby(f,lambda line: line.startswith(':Entry')):
        if not key:
            group = list(group)
            print(group)

yields

['- Namen', 'John Doen', 'n', '- Daten', '20/12/1979n']
['n', '-Namen', 'Jane Doen', '- Daten', '21/12/1979n']

Or, to process the groups, you don't really need to convert group to a list:

with open(filename,'r') as f:
    for key,group in it.groupby(f,lambda line: line.startswith(':Entry')):
        if not key:
            for line in group:
                ...
Friday, July 2, 2021
 
BetaRide
answered 5 Months ago
58

Try this:

import re
re.split(r'[,;]+', 'This,is;a,;string')
> ['This', 'is', 'a', 'string']
Wednesday, August 4, 2021
 
keisar
answered 4 Months ago
99

Here is a pythonic solution:

names = ['blue v orange', 'white v black', 'red v brown']

x, y = list(zip(*(k.split(' v ') for k in names)))

x  # ('blue', 'white', 'red')
y  # ('orange', 'black', 'brown')
Friday, August 6, 2021
 
MassiveAttack
answered 4 Months ago
50

You can use a list comprehension to create new list of lists with all the sentences split:

[lst[0].split() for lst in list_of_lists]

Now you can loop through this and find the list matching a condition:

for sublist in list_of_lists:
    if 'doing' in sublist:
        sublist.append('something')

or searching case insensitively, use any() and a generator expression; this will the minimum number of words to find a match:

for sublist in list_of_lists:
    if any(w.lower() == 'doing' for w in sublist):
        sublist.append('something')
Sunday, August 22, 2021
 
borrible
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share