Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a python string at a delimiter but a specific one

Tags:

python

Is there a way to split a python string without using a for loop that basically splits a string in the middle to the closest delimiter.

Like:

The cat jumped over the moon very quickly.

The delimiter would be the space and the resulting strings would be:

The cat jumped over
the moon very quickly.

I see there is a count where I can see how many spaces are in there (Don't see how to return their indexes though). I could then find the middle one by dividing by two, but then how to say split on this delimiter at this index. Find is close but it returns the first index (or right first index using rfind) not all the indexes where " " is found. I might be over thinking this.

like image 234
Codejoy Avatar asked Dec 06 '22 10:12

Codejoy


2 Answers

This should work:

def split_text(text):
    middle = len(text)//2
    under = text.rfind(" ", 0, middle)
    over = text.find(" ", middle)
    if over > under and under != -1:
        return (text[:,middle - under], text[middle - under,:])
    else:
        if over is -1:
              raise ValueError("No separator found in text '{}'".format(text))
        return (text[:,middle + over], text[middle + over,:])

it does not use a for loop, but probably using a for loop would have better performance.

I handle the case where the separator is not found in the whole string by raising an error, but change raise ValueError() for whatever way you want to handle that case.

like image 61
spaniard Avatar answered Dec 29 '22 01:12

spaniard


You can use min to find the closest space to the middle and then slice the string.

s = "The cat jumped over the moon very quickly."

mid = min((i for i, c in enumerate(s) if c == ' '), key=lambda i: abs(i - len(s) // 2))

fst, snd = s[:mid], s[mid+1:]

print(fst)
print(snd)

Output

The cat jumped over
the moon very quickly.
like image 30
Olivier Melançon Avatar answered Dec 28 '22 23:12

Olivier Melançon