'Create a function without split in python

I'm trying to create a function for agrupation 6 to 6 letters of a sentence, but without use split function.

My code is:

test="the world is mine today" 

def agru_letters(phrase):
    data = [] 
    for i in range(len(phrase) - 5):
        data.append(phrase[i:i+6])

print(agru_letters(phrase))

and the output that I want is:

['thewor',
 'heworl',
 'eworld',
 'worldi',
 'orldis',
 'rldism',
 'ldismi',
 'dismin',
 'ismine',
 'sminet',
 'mineto',
 'inetod',
 'netoda',
 'etoday']


Solution 1:[1]

@PandasaPD beat me to it. I was busy adding steps and variable lengths.

def agru_letters(phrase, length=6, step=1):
  """
  return a list of 'words' of length length 
  that act like a moving window across the phrase 
  in jumps of step ignorening spaces
  """
  words = list()
  sanitized = phrase.replace(" ", "")
  for position in range(0, len(sanitized) - length + 1, step):
    words.append(sanitized[position:position+length])

  return words

Solution 2:[2]

As mentioned in the comments, you didn't return data and you need to remove the spaces from the supplied string. Additionally, you attempt to call your function by supplying phrase, which isn't defined in your outer scope, which would throw a NameError. Fixing these issues:

test = "the world is mine today"

def agru_letters(phrase):
    phrase = phrase.replace(' ', '')
    data = [] 
    for i in range(len(phrase) - 5):
        data.append(phrase[i:i+6])
    return data

print(agru_letters(test))

You could also make the code's intent clearer using windowed from more-itertools:

from more_itertools import windowed

test = "the world is mine today"

def agru_letters(phrase):
    phrase = phrase.replace(' ', '')
    data = []
    for i in windowed(phrase, 6):
        data.append(''.join(i))
    return data

print(agru_letters(test))

You might also consider making the length of substring an argument to agru_letters, and/or using a list comprehension for brevity:

from more_itertools import windowed

test = "the world is mine today"

def agru_letters(phrase, length):
    phrase = phrase.replace(' ', '')
    return [''.join(i) for i in windowed(phrase, length)]

print(agru_letters(test, 6))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AMG
Solution 2