Skip to content Skip to sidebar Skip to footer

Split Python String Every Nth Character Iterating Over Starting Character

I'm trying to find an elegant way to split a python string every nth character, iterating over which character to start with. For example, suppose I have a string containing the fo

Solution 1:

Simple way is to use string slicing together with list comprehensions:

s = 'ANDTLGY'
[s[i:i+3] for i inrange(len(s)-2)]
#output:
['AND', 'NDT', 'DTL', 'TLG', 'LGY']

Solution 2:

a='ANDTLGY'defnlength_parts(a,n):
    returnmap(''.join,zip(*[a[i:] for i inrange(n)]))

print nlength_parts(a,3)

hopefully you can explain to the professor how it works ;)

Solution 3:

how about

a='ANDTLGY'

def chopper(s,chop=3):
     if len(s) < chop:
        return []
     return [s[0:chop]] + chopper(s[1:],chop)

this returns

['AND', 'NDT', 'DTL', 'TLG', 'LGY']

Post a Comment for "Split Python String Every Nth Character Iterating Over Starting Character"