I have the following string:
'ABC DEF GHI JKL MNO'
Is there any way to divide the string into 2 chunks by the, for example, 3rd occurrence of delimiter ' ' (space)?
My desired output for that particular scenario (3rd delimiter) would be:
['ABC DEF GHI', 'JKL MNO']
I've tried split, rsplit, rpartition... but none of them seems to be built for this kind of scenarios.
CodePudding user response:
You can first split the string
to a list
by whitespace and get first nth
element of the list and join them by whitspace
the_string = 'ABC DEF GHI JKL MNO'
nth = 2
lst = the_string.split()
print(" ".join(lst[:nth]))
print(" ".join(lst[nth:]))
CodePudding user response:
One of the approach:
n = 3
data = 'ABC DEF GHI JKL MNO'
# Split on ' '
groups = data.split(" ")
# Create list from with join using ' '
out = [" ".join(groups[:n]), " ".join(groups[n:])]
print (out)
Output:
['ABC DEF GHI', 'JKL MNO']
CodePudding user response:
Obligatory regex based solution! https://xkcd.com/208/
Simple string processing is probably the correct way to do it, but if you want a one liner then you can try:
import re
re.match("^([^ ] ? [^ ] ? [^ ] ?) (.*)$", string).groups()
We create two capture groups. The first must include anything that isn't our delimiter three times separated by our delimiter. Then the delimiter and anything else. Then we read those two groups out giving us the split we want.
So does this work? Yes. Can you be sure of that without writing a bunch of tests? No, not really. Which is why you are probably better off with one of the simpler split and concat methods.