2

My Python code is supposed to output an array with a string divided by 5 chars. I do not understand the logic here:

string = 'j3h1273172' # example
def getStringSplitBy(num=5, string):
     for i in range(len(string)):
         print string[i+num]

The output should be:

['j3h12','73172']
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378

5 Answers5

3

You can try like this,

>>> [string[:5], string[5:]]
['j3h12', '73172']

Function:

>>> def get_string_split_by(num, string):
...   string_len = len(string)
...   items = []
...   for ix in range(0,string_len, num):
...     items.append(string[ix:ix+num])
...   return items

>>> get_string_split_by(5, 'j3h1273172')
['j3h12', '73172']
>>> get_string_split_by(5, 'j3h127317212345')
['j3h12', '73172', '12345']
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
2

Use list-comprehension:

def strings(num,string):
    print [string[i*num:(i+1)*num] for i in range(len(string)/num)]
Shapi
  • 5,493
  • 4
  • 28
  • 39
2

There's no any logic in that function, since it has syntax errors and however it doesn't work as expected. You can simply use:

def get_string_split_by(num, string):
    return string[:num], string[num:]
cdonts
  • 9,304
  • 4
  • 46
  • 72
2

I think itertools provides a recipe for this task:

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
1

You need to use Python's string slicing to divide the string up. The code you posted was grabbing single characters instead of sets of characters.

This code will divide the string into pieces. Also, num should come second since it is an optional parameter.

def getStringSplitBy(string, num=5):
    # Take the length of the string divided by num to figure out how many
    # slices you'll end up with
    for i in range(len(string)//num):
        # Slice the string in chuncks that are num long
        yield string[num*i:num*(i+1)] # Yield to make this an iterable

string = 'j3h1273172' # example
result = list(getStringSplitBy(string,5))
print(result) # prints ['j3h12', '73172']
Caleb Mauer
  • 662
  • 6
  • 11