Home > Back-end >  Extract words as couple from string python
Extract words as couple from string python

Time:06-08

how can I extract each couple of words from a string using python?

For e.g. I have a string divided by space like : "I like python and stackoverflow"

I want: ["I like", "python and", "stackoverflow"]

CodePudding user response:

arr = "I like python and stackoverflow".split(" ")
[" ".join(arr[i:i   2]) for i in range(0, len(arr), 2)]
# ['I like', 'python and', 'stackoverflow']

CodePudding user response:

Try this.

def func(s):
    s = s.split(' ')
    if len(s)%2: s.append('')
    out = [(s[a] ' ' s[a 1]).strip() for a in range(0,len(s),2)]
        
    return out

string = "I like python and stackoverflow"
print(func(string))

OUTPUT ['I like', 'python and', 'stackoverflow']

CodePudding user response:

If you need a regex, try this one:

\w (?:$|\s\w )

https://regex101.com/r/3wW2bo/1

CodePudding user response:

The below answer will scale given parameters, for easiness to understand I didn't make it a oneliner.

def split_n(your_string, step, separator=' '):
    result = []

    # we split it first normally
    your_string = your_string.split(separator)

    # then we combine based on your step choice
    for i in range(0, len(your_string), step):
        result.append(separator.join(your_string[i:i   step]))

    return result


s = "I like python and StackOverflow"

print(split_n(your_string=s, step=2, separator=' '))

>>> ['I like', 'python and', 'stackoverflow']
  • Related