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.
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.
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)
The cat jumped over
the moon very quickly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With