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 ;)
Post a Comment for "Split Python String Every Nth Character Iterating Over Starting Character"