DGGB
DGGB

Reputation: 91

Python split string every n character

I need help finding a way to split a string every nth character, but I need it to overlap so as to get all the

An example should be clearer:

I would like to go from "BANANA" to "BA", "AN", "NA", "AN", "NA", "

Here's my code so far

import string

import re



def player1(s):

    pos1 = []

    inP1 = "AN"

    p = str(len(inP1))

    n = re.findall()

    for n in range(len(s)):

        if s[n] == inP1:

            pos1.append(n)

    points1 = len(pos1)

    return points1


if __name__ == '__main__':

    = "BANANA"

Upvotes: 1

Views: 4555

Answers (3)

Hagbart
Hagbart

Reputation: 105

This will iterate over each letter in the word banana, 0 through 6.

Then print each letter plus the next letter. Else statement for when the word reaches the last letter.

def splitFunc(word):
    for i in range(0, len(word)-1):
        if i < len(word):
            print(word[i] + word[i+1])
        else:
            break

splitFunc("BANANA")

Hope this helps

Upvotes: 1

Itzhak Eretz Kdosha
Itzhak Eretz Kdosha

Reputation: 543

Those are called n-grams.

This should work :)

text = "BANANA"
n = 2
chars = [c for c in text]
ngrams = []
for i in range(len(chars)-n + 1):
  ngram = "".join(chars[i:i+n])
  ngrams.append(ngram)
print(ngrams)

output: ['BA', 'AN', 'NA, 'AN', 'NA']

Upvotes: 0

Andrew McDowell
Andrew McDowell

Reputation: 2980

You can do this pretty simply with list comprehension;

input_string = "BANANA"
[input_string[i]+input_string[i+1] for i in range(0,len(input_string)-1)]

or for every nth character:

index_range = 3
[''.join([input_string[j] for j in range(i, i+index_range)]) for i in range(0,len(input_string)-index_range+1)]

Upvotes: 2

Related Questions