简体   繁体   中英

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 following:

ANDTLGY

I want to split the string into a set of 3 characters looking like this:

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

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

s = 'ANDTLGY'
[s[i:i+3] for i in range(len(s)-2)]
#output:
['AND', 'NDT', 'DTL', 'TLG', 'LGY']
a='ANDTLGY'
def nlength_parts(a,n):
    return map(''.join,zip(*[a[i:] for i in range(n)]))

print nlength_parts(a,3)

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

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM