Skip to content Skip to sidebar Skip to footer

Partitioning A String Based On A Search Term In Python?

Given a string: x = 'foo test1 test1 foo test2 foo' I want to partition the string by foo, so that I get something along the lines of: ['foo', 'test1 test1 foo', 'test2 foo'] (p

Solution 1:

Maybe not the prettiest approach, but concise and straightfoward:

[part + 'foo' for part in g.split('foo')][:-1]

Output:

['foo', ' test1 test1 foo', ' test2 foo']

Solution 2:

You can use str.partition for your case :

deffind_foo(x):
    result = []
    while x:
        before, _, x = x.partition("foo")
        result.append(before + "foo")
    return result

>>> find_foo('foo test1 test1 foo test2 foo')
>>> ['foo', ' test1 test1 foo', ' test2 foo']

Solution 3:

Had you thought about iterating over the string and using a start position for your searches? This can often turn out to be faster than chopping the strings up as you go. This might work for you:

x = 'foo test1 test1 foo test2 foo'  

def findall(target, s):
    lt =len(target)
    ls = len(s)
    pos = 0
    result = []
    whilepos < ls:
        fpos = s.find(target, pos)+lt
        result.append(s[pos:fpos])
        pos = fpos
    return result

print(findall("foo", x))

Solution 4:

You could use look behind positive (?<=) regex expression like

In [515]: string = 'foo test1 test1 foo test2 foo'

In [516]: re.split('(?<=foo)\s', string)
Out[516]: ['foo', 'test1 test1 foo', 'test2 foo']

And,

In[517]: [x.split() for x in re.split('(?<=foo)\s', string)]Out[517]: [['foo'], ['test1', 'test1', 'foo'], ['test2', 'foo']]

Solution 5:

Try this one

x = 'foo test1 test1 foo test2 foo'  

word = 'foo'
out = []
while word in x:
    pos = x.index(word)
    l = len(word)
    out.append( x[:int(pos)+l])
    x = x[int(pos)+l:]

print out

Output :

['foo', ' test1 test1 foo', ' test2 foo']

Post a Comment for "Partitioning A String Based On A Search Term In Python?"